<?php

namespace App\Service\Kms\Task;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Models\BaseModel;
use App\Models\Clickhouse\Guanyuan\GyCloseShopCHModel;
use App\Models\Clickhouse\Guanyuan\GyShopSignCHModel;
use App\Models\Common\AmapAreaModel;
use App\Models\Guanyuan\GuanyuanSyncShopBusinessModel;
use App\Models\Kms\Album\AlbumResourceModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrderTagsMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageMappingModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Models\Kms\Task\DailyTaskLogsModel;
use App\Models\Kms\Task\TaskModel;
use App\Models\Kms\Task\TaskNodesModel;
use App\Models\Kms\Task\TaskTemplateNodesModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\BaseService;
use App\Service\Common\AreaService;
use App\Service\Fee\FeishuApply\FeeAnnualOrderService;
use App\Service\Kms\Home\HomeService;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\OpenShop\Feishu\PermissionService;
use App\Service\OpenShop\Organization\WarZoneService;
use App\Service\Renew\RenewOrderService;
use App\Service\Shop\ShopService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use App\Enums\BaseErrorCode;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Library\Rms\RmsShopApi;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\OpenShop\Common\OpenShopUserTaskTargetModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\SiteLocation\SiteLocationService;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\ValidationException;

class TaskTotalService extends BaseService
{

    const SOURCE_1 = 1;
    const SOURCE_2 = 2;
    const SOURCE_3 = 3;
    const SOURCE_4 = 4;
    const SOURCE_5 = 5;
    const SOURCE_6 = 6;
    const SOURCE_7 = 7;

    const  SOURCE_TEXT_MAPPING = [
        self::SOURCE_1 => '选址任务',// 原选址(待指派开发-开店)
        self::SOURCE_2 => '房源任务',// 原房源
        self::SOURCE_3 => '筹备任务',// 原开店（除待指派开发之外的）
        self::SOURCE_4 => '开业任务',// 原增长
        self::SOURCE_5 => '日常任务',// 新日常任务
        self::SOURCE_6 => '督导任务',// 开业任务 + 日常任务
        self::SOURCE_7 => '勘址任务',
    ];

    const  TYPE_1 = 1;
    const  TYPE_2 = 2;
    const  TYPE_3 = 3;
    const  TYPE_4 = 4;
    const  TYPE_5 = 5;
    const  TYPE_6 = 6;
    const  TYPE_7 = 7;

    const  TYPE_8  = 8;
    const  TYPE_9  = 9;
    const  TYPE_10 = 10;
    const  TYPE_11 = 11;
    const  TYPE_12 = 12;
    const  TYPE_13 = 13;
    const  TYPE_14 = 14;

    const  TYPE_15 = 15;
    const  TYPE_16 = 16;
    const  TYPE_17 = 17;
    const  TYPE_18 = 18;

    const TYPE_20 = 20;
    const TYPE_21 = 21;
    const TYPE_22 = 22;
    const TYPE_23 = 23;

    const TYPE_25 = 25;
    const TYPE_26 = 26;
    const TYPE_27 = 27;
    const TYPE_28 = 28;

    const TYPE_29 = 29;
    const TYPE_30 = 30;
    const TYPE_31 = 31;
    const TYPE_32 = 32;
    const TYPE_33 = 33;
    const TYPE_34 = 34;

    const  TYPE_TEXT_MAPPING = [
        self::TYPE_1 => '选址待提交',
        self::TYPE_2 => '选址待修改',
        self::TYPE_3 => '已落址',
        self::TYPE_4 => '选址待审批',//（含待审核）
        self::TYPE_5 => '合同待上传',
        self::TYPE_6 => '开发待指派',
        self::TYPE_7 => '商家待确认',

        self::TYPE_8  => '线索待完善',// a)待自评b)房源线索c）待评估 不展示：已关闭
        self::TYPE_9  => '线索待审批',
        self::TYPE_10 => '线索待修改',
        self::TYPE_11 => '房源线索提交',
        self::TYPE_12 => '已上架房源',
        self::TYPE_13 => '线索待分配',
        self::TYPE_14 => '房源待评估',

        self::TYPE_15 => '确认建店信息',
        self::TYPE_16 => '确认施工进场',
        self::TYPE_17 => '确认施工完成',
        self::TYPE_18 => '已完成任务',

        self::TYPE_20 => '提交开业报告',
        self::TYPE_21 => '开业报告审批中',
        self::TYPE_22 => '修改开业报告',
        self::TYPE_23 => '开业报告已完成',

        self::TYPE_25 => '日常任务待提交',
        self::TYPE_26 => '日常任务待修改',
        self::TYPE_27 => '日常任务待审批',
        self::TYPE_28 => '日常任务已结束',

        self::TYPE_29 => '待跟进',
        self::TYPE_30 => '无线索',
        self::TYPE_31 => '有效线索',
        self::TYPE_32 => '有效房源',
        self::TYPE_33 => '已确址',
        self::TYPE_34 => '已完成',
    ];


    // 门店tab-状态
    const  SHOP_TYPE_TEXT_MAPPING = [
        self::TYPE_1  => '开发待指派',
        self::TYPE_2  => '待提交',
        self::TYPE_3  => '流程中',
        self::TYPE_4  => '待确认建店',
        self::TYPE_5  => '待施工入场',
        self::TYPE_6  => '待施工完成',
        self::TYPE_7  => '待开业',
        self::TYPE_8  => '正常营业',
        self::TYPE_9  => '暂停营业',
        self::TYPE_10 => '昨日活跃',
        self::TYPE_11 => '昨日休眠',
        self::TYPE_13 => '合同待签署',
    ];

    // 选址tab
    const SHOP_TAG_1 = 1;
    const SHOP_TAG_2 = 2;
    const SHOP_TAG_3 = 3;
    const SHOP_TAG_4 = 4;
    const SHOP_TAG_5 = 5;

    const SHOP_TAG_TEXT_MAPPING = [
        self::SHOP_TAG_1 => '选址活跃',
        self::SHOP_TAG_2 => '选址沉默',
        self::SHOP_TAG_3 => '筹备正常',
        self::SHOP_TAG_4 => '筹备异常',
        self::SHOP_TAG_5 => '开业报告未完成',
    ];

    const SHOP_TAG_VALUE_MAPPING = [
        self::SHOP_TAG_1 => ['活跃客户'],//活跃客户(正常),定向选址(正常)
        self::SHOP_TAG_2 => ['沉默客户'],//暂无计划(沉默),高风险流失(沉默)
        self::SHOP_TAG_3 => ['筹备正常'],//筹备正常
        self::SHOP_TAG_4 => ['筹备异常'],//筹备异常
        self::SHOP_TAG_5 => [
            CruiseOrderModel::STATUS_NOT_SUBMIT, CruiseOrderModel::STATUS_NOT_REVIEW,
            CruiseOrderModel::STATUS_WAIT_MODIFY_EXT, CruiseOrderModel::STATUS_NOT_MODIFY
        ],//包括了未提交，审批中和修改中
    ];


    const STORE_TYPE_1 = 1;
    const STORE_TYPE_2 = 2;
    const STORE_TYPE_3 = 3;
    const STORE_TYPE_4 = 4;

    const STORE_TAG_TEXT_MAPPING  = [
        self::STORE_TYPE_1 => '商场',
        self::STORE_TYPE_2 => '街边',
        self::STORE_TYPE_3 => '景区',
        self::STORE_TYPE_4 => '高校',
    ];
    const STORE_TAG_VALUE_MAPPING = [
        self::STORE_TYPE_1 => '商场店',
        self::STORE_TYPE_2 => '街边店',
        self::STORE_TYPE_3 => '景区店',
        self::STORE_TYPE_4 => '学校店',
    ];

    const SHOP_GRADE_1 = 1;
    const SHOP_GRADE_2 = 2;
    const SHOP_GRADE_3 = 3;
    const SHOP_GRADE_4 = 4;
    const SHOP_GRADE_5 = 5;

    const SHOP_GRADE_TEXT_MAPPING = [
        self::SHOP_GRADE_1 => '明星',
        self::SHOP_GRADE_2 => '金牛',
        self::SHOP_GRADE_3 => '瘦狗',
        self::SHOP_GRADE_4 => '问题',
        self::SHOP_GRADE_5 => 'ST',
    ];

    const SITE_LOCATION_SEARCH_MAPPING = [
        self::TYPE_6 => '开发待指派',
        self::TYPE_1 => '选址待提交',
        self::TYPE_4 => '选址待审批',//（含待审核）
        self::TYPE_2 => '选址待修改',
        self::TYPE_7 => '商家待确认',
        self::TYPE_5 => '合同待上传',
        self::TYPE_3 => '已落址',
    ];

    const SITE_LOCATION_SEARCH_TAG_MAPPING = [
        self::SHOP_TAG_1 => '选址活跃',
        self::SHOP_TAG_2 => '选址沉默',
    ];

    const SITE_LOCATION_SEARCH_TAG_ID_MAPPING = [
        self::SHOP_TAG_1 => [OpenShopOrderTagsMappingModel::TAG_TYPE_14, OpenShopOrderTagsMappingModel::TAG_TYPE_17],//活跃客户(正常),定向选址(正常)
        self::SHOP_TAG_2 => [OpenShopOrderTagsMappingModel::TAG_TYPE_16, OpenShopOrderTagsMappingModel::TAG_TYPE_18],//暂无计划(沉默),高风险流失(沉默)
    ];


    /**
     * 列表页数据查询汇总【包含特殊审批人】 不同角色返回不同数据
     * @param int $rmsUserId
     * @param array $userIds
     * @param array $search
     * @return array
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function countTotal(int $rmsUserId, array $userIds, array $search): array
    {
        $getUserRole   = UserRoleService::getUserRole($rmsUserId);
        $role          = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        $roleDesc      = $getUserRole['desc'] ?? '';
        $provinceCodes = $getUserRole['userResponsibleArea']['area']['province'] ?? [];
        $cityCodes     = $getUserRole['userResponsibleArea']['area']['city'] ?? [];
        $areaCodes     = $getUserRole['userResponsibleArea']['area']['district'] ?? [];
        $allArea       = $getUserRole['userResponsibleArea']['all'] ?? false;

        // 模糊搜索
        $searchRes = self::searchWhereByName($search);

        $data = [
            'role'          => $role,
            'provinceCodes' => $provinceCodes,
            'cityCodes'     => $cityCodes,
            'areaCodes'     => $areaCodes,
            'userIds'       => array_unique(array_merge($userIds, $searchRes['rmsUserIds'])),
            'allArea'       => $allArea,
            'rmsUserId'     => $rmsUserId,
            'search'        => $search,
            'orderNos'      => $searchRes['orderNos'],
        ];
        // 所有权限-查看
        if ($role == UserRoleService::ROLE_SPECIAL_0) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);

            // 房源
            $countHouseAll = self::countHouse($data, 0);

            // 筹备
            $countPrepareAll = self::countPrepare($data, 0);

            // 开业报告
            $countCruiseAll = self::countCruise($data, 0);

            // 新日常任务
            $countDailyAll = self::countDaily($data, 0);

        }

        // 观察者-查看
        if ($role == UserRoleService::ROLE_BASE_OBSERVER) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);

            // 房源
            $countHouseAll = self::countHouse($data, 0);

            // 筹备
            $countPrepareAll = self::countPrepare($data, 0);

            // 开业报告
            $countCruiseAll = self::countCruise($data, 0);

            // 新日常任务
            $countDailyAll = self::countDaily($data, 0);

        }

        // 战区负责人
        if ($role == UserRoleService::ROLE_BASE_WAR_REGION) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);

            // 房源
            $countHouseAll = self::countHouse($data, 0);

            // 筹备
            $countPrepareAll = self::countPrepare($data, 0);

            // 开业报告
            $countCruiseAll = self::countCruise($data, 0);

            // 新日常任务
            $countDailyAll = self::countDaily($data, 0);
            $countDaily    = self::countDaily($data, 1);
        }

        // 省总  1、指派开发顾问 2、房源审批 3、选址审批 4、创建临时任务
        if ($role == UserRoleService::ROLE_BASE_PROVINCE) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);
            $countSiteLocation    = self::countSiteLocation($data, 1);

            // 房源
            $countHouseAll = self::countHouse($data, 0);
            $countHouse    = self::countHouse($data, 1);

            // 筹备
            $countPrepareAll = self::countPrepare($data, 0);

            // 开业报告
            $countCruiseAll = self::countCruise($data, 0);

            // 新日常任务
            $countDailyAll = self::countDaily($data, 0);
            $countDaily    = self::countDaily($data, 1);

        }

        // 城市经理 1、创建临时任务
        if ($role == UserRoleService::ROLE_BASE_CITY_MANAGER) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);

            // 房源
            $countHouseAll = self::countHouse($data, 0);

            // 筹备
            $countPrepareAll = self::countPrepare($data, 0);

            // 开业报告
            $countCruiseAll = self::countCruise($data, 0);

            // 新日常任务
            $countDailyAll = self::countDaily($data, 0);
            $countDaily    = self::countDaily($data, 1);
        }

        // 开发城市经理
        if ($role == UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);
            $countSiteLocation    = self::countSiteLocation($data, 1);

            // 房源
            $countHouseAll = self::countHouse($data, 0);
            $countHouse    = self::countHouse($data, 1);

            // 筹备
            $countPrepareAll = self::countPrepare($data, 0);

            // 开业报告
            $countCruiseAll = self::countCruise($data, 0);

            // 新日常任务
            $countDailyAll = self::countDaily($data, 0);
        }

        // 选址开发 1、提交房源（含房源线索完善、房源选址评估、房源修改） 2、提交选址报告 3、修改选址报告 4、上传合同
        if ($role == UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT) {

            if ($allArea) {// 附属营运负责人==总部-查看所有
                // 选址
                $countSiteLocationAll = self::countSiteLocation($data, 0);
                $countSiteLocation    = self::countSiteLocation($data, 1);

                // 房源
                $countHouseAll = self::countHouse($data, 0);
                $countHouse    = self::countHouse($data, 1);

                // 筹备
                $countPrepareAll = self::countPrepare($data, 0);

                // 开业报告
                $countCruiseAll = self::countCruise($data, 0);

                // 新日常任务
                $countDailyAll = self::countDaily($data, 0);
            } else {
                // 选址
                $countSiteLocationAll = self::countSiteLocation($data, 0, 1);
                $countSiteLocation    = self::countSiteLocation($data, 1);

                // 房源
                $countHouseAll = self::countHouse($data, 0, 1);
                $countHouse    = self::countHouse($data, 1);
            }
        }

        // 筹备 1、确认建店信息（填写督导） 2、确认施工进场 3、确认施工完成
        if ($role == UserRoleService::ROLE_BASE_PREPARE) {

            if ($allArea) {// 附属营运负责人==总部-查看所有
                // 选址
                $countSiteLocationAll = self::countSiteLocation($data, 0);

                // 房源
                $countHouseAll = self::countHouse($data, 0);

                // 筹备
                $countPrepareAll = self::countPrepare($data, 0);
                $countPrepare    = self::countPrepare($data, 1);

                // 开业报告
                $countCruiseAll = self::countCruise($data, 0);

                // 新日常任务
                $countDailyAll = self::countDaily($data, 0);
            } else {
                // 筹备
                $countPrepareAll = self::countPrepare($data, 0, 1);
                $countPrepare    = self::countPrepare($data, 1);
            }
        }

        // 督导 1、提交开业报告 2、修改开业报告 3、创建/完成临时任务
        if ($role == UserRoleService::ROLE_BASE_SUPERVISOR) {
            if ($allArea) {// 附属营运负责人==总部-查看所有
                // 选址
                $countSiteLocationAll = self::countSiteLocation($data, 0);

                // 房源
                $countHouseAll = self::countHouse($data, 0);

                // 筹备
                $countPrepareAll = self::countPrepare($data, 0);

                // 开业报告
                $countCruiseAll = self::countCruise($data, 0);
                $countCruise    = self::countCruise($data, 1);

                // 新日常任务
                $countDailyAll = self::countDaily($data, 0);
                $countDaily    = self::countDaily($data, 1);
            } else {
                // 开业报告
                $countCruiseAll = self::countCruise($data, 0);
                $countCruise    = self::countCruise($data, 1);

                // 新日常任务
                $countDailyAll = self::countDaily($data, 0);
                $countDaily    = self::countDaily($data, 1);
            }
        }

        // 大黄蜂 1、选址审批
        if ($role == UserRoleService::ROLE_SPECIAL_1) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);
            $countSiteLocation    = self::countSiteLocation($data, 1);

            // 房源
            $countHouseAll = self::countHouse($data, 0);
            $countHouse    = self::countHouse($data, 1);

            // 勘址
            $countSiteSurveyAll = self::countSiteSurvey($data, 0);

            // 筹备
            $countPrepareAll = self::countPrepare($data, 0);

            // 开业报告
            $countCruiseAll = self::countCruise($data, 0);

            // 新日常任务
            $countDailyAll = self::countDaily($data, 0);

        }

        // 赤瞳 1、房源审批 2、选址审批
        if ($role == UserRoleService::ROLE_SPECIAL_2) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);
            $countSiteLocation    = self::countSiteLocation($data, 1);

            // 房源
            $countHouseAll = self::countHouse($data, 0);
            $countHouse    = self::countHouse($data, 1);

            // 勘址
            $countSiteSurveyAll = self::countSiteSurvey($data, 0);

            // 筹备
            $countPrepareAll = self::countPrepare($data, 0);

            // 开业报告
            $countCruiseAll = self::countCruise($data, 0);

            // 新日常任务
            $countDailyAll = self::countDaily($data, 0);

        }

        // 灵文 1、选址审批 2、审批合同
        if ($role == UserRoleService::ROLE_SPECIAL_3) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);
            $countSiteLocation    = self::countSiteLocation($data, 1);

        }

        // 辰月 1、审批开业报告
        if ($role == UserRoleService::ROLE_SPECIAL_4) {

            // 开业报告
            $countCruiseAll = self::countCruise($data, 0);
            $countCruise    = self::countCruise($data, 1);

        }

        // 胖虎 1、开发待指派
        if ($role == UserRoleService::ROLE_SPECIAL_5) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0);
            $countSiteLocation    = self::countSiteLocation($data, 1);

            if ($allArea) {
                // 房源
                $countHouseAll = self::countHouse($data, 0);

                // 筹备
                $countPrepareAll = self::countPrepare($data, 0);

                // 开业报告
                $countCruiseAll = self::countCruise($data, 0);

                // 新日常任务
                $countDailyAll = self::countDaily($data, 0);
            }

        }

        // 大客户部 勘址任务
        if ($role == UserRoleService::ROLE_BASE_KAM) {

            // 选址
            $countSiteLocationAll = self::countSiteLocation($data, 0, 1);
            $countSiteLocation    = self::countSiteLocation($data, 1);

            // 房源
            $countHouseAll = self::countHouse($data, 0, 1);
            $countHouse    = self::countHouse($data, 1);

            // 勘址
            $countSiteSurveyAll = self::countSiteSurvey($data, 0, 1);
            $countSiteSurvey    = self::countSiteSurvey($data, 1);

        }

        $all = $allChildSite = $allChildPrepare = $allChildDaily = [];
        if (isset($countSiteLocationAll)) {// 选址
            $allChildSite[] = [
                'total'      => array_sum(array_column($countSiteLocationAll, 'count')),
                'source'     => self::SOURCE_1,
                'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_1] ?? '',
                'child'      => $countSiteLocationAll,
            ];
        }
        if (isset($countHouseAll)) {//房源
            $allChildSite[] = [
                'total'      => array_sum(array_column($countHouseAll, 'count')),
                'source'     => self::SOURCE_2,
                'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_2] ?? '',
                'child'      => $countHouseAll,
            ];
        }
        if (isset($countSiteSurveyAll)) {//勘址
            $allChildSite[] = [
                'total'      => array_sum(array_column($countSiteSurveyAll, 'count')),
                'source'     => self::SOURCE_7,
                'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_7] ?? '',
                'child'      => $countSiteSurveyAll,
            ];
        }
        if ($allChildSite) {
            $all[] = [
                'total'      => array_sum(array_column($allChildSite, 'total')),
                'source'     => self::SOURCE_1,
                'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_1] ?? '',
                'child'      => $allChildSite,
            ];
        }
        if (isset($countPrepareAll)) {
            $allChildPrepare[] = [
                'total'      => array_sum(array_column($countPrepareAll, 'count')),
                'source'     => self::SOURCE_3,
                'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_3] ?? '',
                'child'      => $countPrepareAll,
            ];
        }
        if ($allChildPrepare) {
            $all[] = [
                'total'      => array_sum(array_column($allChildPrepare, 'total')),
                'source'     => self::SOURCE_3,
                'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_3] ?? '',
                'child'      => $allChildPrepare,
            ];
        }
        if (isset($countCruiseAll)) {
            $allChildDaily[] = [
                'total'      => array_sum(array_column($countCruiseAll, 'count')),
                'source'     => self::SOURCE_4,
                'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_4] ?? '',
                'child'      => $countCruiseAll,
            ];
        }
        if (isset($countDailyAll)) {
            $allChildDaily[] = [
                'total'      => array_sum(array_column($countDailyAll, 'count')),
                'source'     => self::SOURCE_5,
                'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_5] ?? '',
                'child'      => $countDailyAll,
            ];
        }
        if ($allChildDaily) {
            $all[] = [
                'total'      => array_sum(array_column($allChildDaily, 'total')),
                'source'     => self::SOURCE_6,
                'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_6] ?? '',
                'child'      => $allChildDaily,
            ];
        }


        $ing = $searchSiteSurvey = [];
        if (isset($countSiteSurvey)) {//勘址
            $ing[] =
                [
                    'total'      => array_sum(array_column($countSiteSurvey, 'count')),
                    'source'     => self::SOURCE_7,
                    'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_7] ?? '',
                    'child'      => [
                        'count'    => array_sum(array_column($countSiteSurvey, 'count')),
                        'type'     => self::SOURCE_7,
                        'typeText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_7] ?? '',
                    ],
                ];

            $searchSiteSurvey = [
                'area'  => true,// 地区筛选
                'type'  => [
                    self::TYPE_29 => '待跟进',
                    self::TYPE_30 => '无线索',
                    self::TYPE_31 => '有线索',
                    self::TYPE_32 => '有效房源',
                    self::TYPE_33 => '已确址',
                    self::TYPE_34 => '已完成',
                ],//状态筛选
                'grade' => [
                    CustomerDepartmentTaskModel::GRADE_S => 'S级',
                    CustomerDepartmentTaskModel::GRADE_A => 'A级',
                    CustomerDepartmentTaskModel::GRADE_B => 'B级',
                    CustomerDepartmentTaskModel::GRADE_C => 'C级',
                ],
                'sort'  => [
                    'grade'     => '按网规等级排序',
                    'updatedAt' => '按最近跟进排序',
                ],
            ];
        }
        if (isset($countSiteLocation)) {
            $ing[] =
                [
                    'total'      => array_sum(array_column($countSiteLocation, 'count')),
                    'source'     => self::SOURCE_1,
                    'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_1] ?? '',
                    'child'      => $countSiteLocation,
                ];
        }
        if (isset($countHouse)) {
            $ing[] =
                [
                    'total'      => array_sum(array_column($countHouse, 'count')),
                    'source'     => self::SOURCE_2,
                    'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_2] ?? '',
                    'child'      => $countHouse,
                ];
        }
        if (isset($countPrepare)) {
            $ing[] =
                [
                    'total'      => array_sum(array_column($countPrepare, 'count')),
                    'source'     => self::SOURCE_3,
                    'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_3] ?? '',
                    'child'      => $countPrepare,
                ];
        }
        if (isset($countCruise)) {
            $ing[] =
                [
                    'total'      => array_sum(array_column($countCruise, 'count')),
                    'source'     => self::SOURCE_4,
                    'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_4] ?? '',
                    'child'      => $countCruise,
                ];
        }
        if (isset($countDaily)) {
            $ing[] =
                [
                    'total'      => array_sum(array_column($countDaily, 'count')),
                    'source'     => self::SOURCE_5,
                    'sourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_5] ?? '',
                    'child'      => $countDaily,
                ];
        }
        return [
            'all'              => $all,             // 全部
            'ing'              => $ing,             // 待处理
            'searchSiteSurvey' => $searchSiteSurvey,// 勘址任务搜索
            'user'             => [
                'role'               => $role,
                'roleDesc'           => $roleDesc,
                'allArea'            => $allArea,
                'isShowTask'         => self::checkRolePermissions($role, 1), // 是否展示新建日常任务
                'isShowStaff'        => self::checkRolePermissions($role, 2), // 是否展示员工列表
                'isShowUser'         => self::checkRolePermissions($role, 3), // 是否展示用户列表
                'isShowAddHouseClue' => true,                                 //self::checkRolePermissions($role, 4), // 是否展示新建房源线索
                'isShowCollect'      => self::checkRolePermissions($role, 5), // 是否展示收藏任务
                'provinceCodes'      => $provinceCodes,
                'cityCodes'          => $cityCodes,
                'areaCodes'          => $areaCodes,
            ],// 用户权限信息
        ];
    }

    /**
     * 选址
     * @param array $data
     * @param int $isOperate 0-全部 1-待我处理
     * @param int $isRel
     * @param bool $isTag
     * @return array
     */
    public static function countSiteLocation(array $data, int $isOperate, int $isRel = 0, bool $isTag = false): array
    {
        $getOrderNos = self::searchWhereByFyName($data['search']);
        if ($getOrderNos) {
            $data['orderNos'] = array_unique(array_merge($data['orderNos'], $getOrderNos));
        }
        $baseSql = OpenShopSiteLocationModel::query()
            ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_OPEN_SHOP])
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('orderNo', $data['orderNos']);
            }
            )
            ->when(
                !in_array(
                    $data['role'], [
                        UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT,
                    ]
                ) && ($data['provinceCodes'] || $data['cityCodes'] || $data['areaCodes']), function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->when(
                            $data['provinceCodes'], function ($query) use ($data) {
                            $query->whereIn("provinceCode", $data['provinceCodes']);
                        }
                        )->when(
                            $data['cityCodes'], function ($query) use ($data) {
                            $query->orWhereIn("cityCode", $data['cityCodes']);
                        }
                        )->when(
                            $data['areaCodes'], function ($query) use ($data) {
                            $query->orWhereIn("areaCode", $data['areaCodes']);
                        }
                        );
                    }
                );
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->whereIn("developConsultantId", $data['userIds']);
            }
            )
            ->when(
                $isOperate || $isRel, function ($query) use ($isOperate, $data) {
                $query->where(
                    function ($query) use ($isOperate, $data) {
                        $query->where('developConsultantId', $data['rmsUserId'])
                            ->orWhere(
                                function ($query) use ($isOperate, $data) {
                                    $query->when(
                                        in_array(
                                            $data['role'], [
                                                UserRoleService::ROLE_BASE_PROVINCE,
                                                UserRoleService::ROLE_SPECIAL_1,
                                                UserRoleService::ROLE_SPECIAL_2,
                                                UserRoleService::ROLE_SPECIAL_3,
                                                UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                                            ]
                                        ) && $isOperate, function ($query) use ($data) {
                                        $query->whereRaw("FIND_IN_SET({$data['rmsUserId']}, `handler`) != 0");//现阶段处理人Id 省总和赤瞳
                                    }
                                    );
                                }
                            );
                    }
                );
            }
            );

        $siteSql      = clone $baseSql;
        $siteLocalSql = $siteSql
            ->groupBy('siteStatus')
            ->selectRaw('siteStatus,count(1) num')
            ->get();

        $tagData = [];

        // 关联标签
        if ($isTag) {
            $tagSql          = clone $baseSql;
            $siteLocalTagSql = $tagSql
                ->join('open_shop_order_tags_mapping', 'open_shop_order_tags_mapping.orderNo', '=', 'open_shop_site_locations.orderNo')
                ->where("open_shop_order_tags_mapping.isDeleted", 0)
                ->whereIn(
                    'open_shop_order_tags_mapping.tagId', [
                        OpenShopOrderTagsMappingModel::TAG_TYPE_14, OpenShopOrderTagsMappingModel::TAG_TYPE_17,
                        OpenShopOrderTagsMappingModel::TAG_TYPE_16, OpenShopOrderTagsMappingModel::TAG_TYPE_18
                    ]
                )
                ->groupBy('open_shop_order_tags_mapping.tagId')
                ->selectRaw('open_shop_order_tags_mapping.tagId,count(1) num')
                ->get();

            // 选址活跃
            $siteLocalActive = $siteLocalTagSql
                ->whereIn('tagId', [OpenShopOrderTagsMappingModel::TAG_TYPE_14, OpenShopOrderTagsMappingModel::TAG_TYPE_17])
                ->sum('num');

            // 选址沉默
            $siteLocalTagSilent = $siteLocalTagSql
                ->whereIn('tagId', [OpenShopOrderTagsMappingModel::TAG_TYPE_16, OpenShopOrderTagsMappingModel::TAG_TYPE_18])
                ->sum('num');

            $tagData = [
                [
                    'tag'     => self::SHOP_TAG_1,
                    'tagText' => self::SHOP_TAG_TEXT_MAPPING[self::SHOP_TAG_1] ?? '',
                    'count'   => $siteLocalActive,   // 选址活跃
                ],
                [
                    'tag'     => self::SHOP_TAG_2,
                    'tagText' => self::SHOP_TAG_TEXT_MAPPING[self::SHOP_TAG_2] ?? '',
                    'count'   => $siteLocalTagSilent,// 选址沉默
                ],
            ];
        }

        // 提交选址
        $toBeLocated = $siteLocalSql
            ->whereIn('siteStatus', [OpenShopSiteLocationModel::SITE_STATUS_0, OpenShopSiteLocationModel::SITE_STATUS_1])
            ->sum('num');

        // 选址修改
        $pendingApproval = $siteLocalSql
            ->whereIn('siteStatus', [OpenShopSiteLocationModel::SITE_STATUS_3])
            ->sum('num');

        // 完成落址
        $completed = $siteLocalSql
            ->whereIn('siteStatus', [OpenShopSiteLocationModel::SITE_STATUS_4])
            ->sum('num');

        // 选址审批
        $pendingUpdated = $siteLocalSql
            ->whereIn('siteStatus', [OpenShopSiteLocationModel::SITE_STATUS_2, OpenShopSiteLocationModel::SITE_STATUS_10, OpenShopSiteLocationModel::SITE_STATUS_11])
            ->sum('num');

        // 合同上传
        $contractToBeUpload = $siteLocalSql
            ->whereIn('siteStatus', [OpenShopSiteLocationModel::SITE_STATUS_21])
            ->sum('num');

        // 商家待确认
        $toBeConfirmed = $siteLocalSql
            ->whereIn('siteStatus', [OpenShopSiteLocationModel::SITE_STATUS_20])
            ->sum('num');

        // 开发待指派
        if (($isOperate || $isRel) || (in_array(
                    $data['role'], [
                        UserRoleService::ROLE_BASE_PROVINCE,
                        UserRoleService::ROLE_SPECIAL_5,
                        UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                    ]
                ) && $isOperate)) {
            $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
        }
        $child = self::getOrderNosByProvinceCode($data);

        $toBeDevelopment = OpenShopSiteMissionModel::query()
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->whereIn('dealUid', $data['userIds']);
            }
            )
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('orderNo', $data['orderNos']);
            }
            )
            ->when(
                $child, function ($query) use ($child) {
                $query->whereRaw('orderNo in (' . BaseModel::toSqlWithParam($child) . ')');
            }
            )
            ->where('status', SiteMissionEnum::STATUS_1)
            ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_3)
            ->where('isShow', 1)
            ->where('orderStatus', 1)
            ->count();

        $res = [];
        if ($isOperate) {
            //省总 赤瞳
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_PROVINCE, UserRoleService::ROLE_SPECIAL_2, UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER])) {
                $res = [
                    [
                        'type'     => self::TYPE_6,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_6] ?? '',
                        'count'    => $toBeDevelopment,   // 开发待指派
                    ],
                    [
                        'type'     => self::TYPE_4,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_4] ?? '',
                        'count'    => $pendingUpdated,// 选址审批
                    ],
                ];
            }
            // 选址开发   2、提交选址报告 3、修改选址报告 4、上传合同
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT, UserRoleService::ROLE_BASE_KAM])) {
                $res = [
                    [
                        'type'     => self::TYPE_1,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_1] ?? '',
                        'count'    => $toBeLocated,// 提交选址
                    ],
                    [
                        'type'     => self::TYPE_2,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_2] ?? '',
                        'count'    => $pendingApproval,// 选址修改
                    ],
                    [
                        'type'     => self::TYPE_5,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_5] ?? '',
                        'count'    => $contractToBeUpload,// 合同上传
                    ],
                ];
            }
            // 赤瞳,大黄蜂,灵文   选址审批
            if (in_array($data['role'], [UserRoleService::ROLE_SPECIAL_1, UserRoleService::ROLE_SPECIAL_3])) {
                $res = [
                    [
                        'type'     => self::TYPE_4,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_4] ?? '',
                        'count'    => $pendingUpdated,// 选址审批
                    ],
                ];
            }
            // 胖虎   开发待指派
            if (in_array($data['role'], [UserRoleService::ROLE_SPECIAL_5])) {
                $res = [
                    [
                        'type'     => self::TYPE_6,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_6] ?? '',
                        'count'    => $toBeDevelopment,   // 开发待指派
                    ],
                ];
            }
        } else {
            // 选址开发
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT, UserRoleService::ROLE_BASE_KAM])) {
                $res = [
                    [
                        'type'     => self::TYPE_1,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_1] ?? '',
                        'count'    => $toBeLocated,// 提交选址
                    ],
                    [
                        'type'     => self::TYPE_4,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_4] ?? '',
                        'count'    => $pendingUpdated,// 选址审批
                    ],
                    [
                        'type'     => self::TYPE_2,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_2] ?? '',
                        'count'    => $pendingApproval,// 选址修改
                    ],
                    [
                        'type'     => self::TYPE_7,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_7] ?? '',
                        'count'    => $toBeConfirmed,// 商家待确认
                    ],
                    [
                        'type'     => self::TYPE_5,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_5] ?? '',
                        'count'    => $contractToBeUpload,// 合同上传
                    ],
                    [
                        'type'     => self::TYPE_3,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_3] ?? '',
                        'count'    => $completed,// 完成落址
                    ],
                ];
            } else {
                $res = [
                    [
                        'type'     => self::TYPE_6,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_6] ?? '',
                        'count'    => $toBeDevelopment,   // 开发待指派
                    ],
                    [
                        'type'     => self::TYPE_1,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_1] ?? '',
                        'count'    => $toBeLocated,// 提交选址
                    ],
                    [
                        'type'     => self::TYPE_4,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_4] ?? '',
                        'count'    => $pendingUpdated,// 选址审批
                    ],
                    [
                        'type'     => self::TYPE_2,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_2] ?? '',
                        'count'    => $pendingApproval,// 选址修改
                    ],
                    [
                        'type'     => self::TYPE_7,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_7] ?? '',
                        'count'    => $toBeConfirmed,// 商家待确认
                    ],
                    [
                        'type'     => self::TYPE_5,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_5] ?? '',
                        'count'    => $contractToBeUpload,// 合同上传
                    ],
                    [
                        'type'     => self::TYPE_3,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_3] ?? '',
                        'count'    => $completed,// 完成落址
                    ],
                ];
            }
        }

        if (!$tagData) {
            return $res;
        }
        return ['data' => $res, 'tagData' => $tagData];
    }


    /**
     * 房源
     * @param array $data
     * @param int $isOperate 0-全部 1-待我处理
     * @param int $isRel
     * @return array
     */
    public static function countHouse(array $data, int $isOperate, int $isRel = 0): array
    {
        $houseSql = OpenShopSiteLocationModel::query()
            ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_HOUSING])
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('orderNo', $data['orderNos']);
            }
            )
            ->when(
                $data['search']['fyName'], function ($query) use ($data) {
                //区分编号与地址搜索
                if (strpos($data['search']['fyName'], 'fy') !== false ||
                    strpos($data['search']['fyName'], 'FY') !== false ||
                    strpos($data['search']['fyName'], 'Fy') !== false ||
                    strpos($data['search']['fyName'], 'fY') !== false ||
                    is_numeric($data['search']['fyName'])) {
                    $query->where('orderNo', $data['search']['fyName']);
                } else {
                    $query->where(
                        function ($query) use ($data) {
                            $query->orWhere('address', 'like', "%{$data['search']['fyName']}%")
                                ->orWhere('siteAddress', 'like', "%{$data['search']['fyName']}%")
                                ->orWhere('cityArea', 'like', "%{$data['search']['fyName']}%");
                        }
                    );
                }
            }
            )
            ->when(
                !in_array(
                    $data['role'], [
                        UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT,
                    ]
                ) && ($data['provinceCodes'] || $data['cityCodes'] || $data['areaCodes']), function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->when(
                            $data['provinceCodes'], function ($query) use ($data) {
                            $query->whereIn("provinceCode", $data['provinceCodes']);
                        }
                        )->when(
                            $data['cityCodes'], function ($query) use ($data) {
                            $query->orWhereIn("cityCode", $data['cityCodes']);
                        }
                        )->when(
                            $data['areaCodes'], function ($query) use ($data) {
                            $query->orWhereIn("areaCode", $data['areaCodes']);
                        }
                        );
                    }
                );
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->whereIn('developConsultantId', $data['userIds'])
                            ->orWhereIn('createdByUid', $data['userIds']);
                    }
                );
            }
            )
            ->when(
                $isOperate || $isRel, function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->where('developConsultantId', $data['rmsUserId'])
                            ->orWhere(
                                function ($query) use ($data) {
                                    $query->when(
                                        in_array(
                                            $data['role'], [
                                                UserRoleService::ROLE_BASE_PROVINCE,
                                                UserRoleService::ROLE_SPECIAL_1,
                                                UserRoleService::ROLE_SPECIAL_2,
                                                UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                                            ]
                                        ), function ($query) use ($data) {
                                        $query->whereRaw("FIND_IN_SET({$data['rmsUserId']}, `handler`) != 0");//现阶段处理人Id 省总和赤瞳
                                    }
                                    );
                                }
                            );
                    }
                );
            }
            )
            ->groupBy('clueStatus')
            ->selectRaw('clueStatus,count(1) num')
            ->get();

        // 房源线索完善
        $housePerfectCount = $houseSql
            ->whereIn('clueStatus', [OpenShopSiteLocationModel::CLUE_STATUS_12, OpenShopSiteLocationModel::CLUE_STATUS_2, OpenShopSiteLocationModel::CLUE_STATUS_13])
            ->sum('num');

        // 房源审批中
        $houseInApprovalCount = $houseSql
            ->whereIn('clueStatus', [OpenShopSiteLocationModel::CLUE_STATUS_3, OpenShopSiteLocationModel::CLUE_STATUS_11])
            ->sum('num');

        // 房源待修改
        $houseModifyCount = $houseSql
            ->whereIn('clueStatus', [OpenShopSiteLocationModel::CLUE_STATUS_4])
            ->sum('num');

        // 待使用房源
        $houseUseCount = $houseSql
            ->whereIn('clueStatus', [OpenShopSiteLocationModel::CLUE_STATUS_5])
            ->sum('num');

        // 房源分配
        $houseDistributeCount = OpenShopSiteLocationModel::query()
            ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_HOUSING])
            ->whereIn('clueStatus', [OpenShopSiteLocationModel::CLUE_STATUS_1])
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('orderNo', $data['orderNos']);
            }
            )
            ->when(
                $data['provinceCodes'] || $data['cityCodes'] || $data['areaCodes'], function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->when(
                            $data['provinceCodes'], function ($query) use ($data) {
                            $query->whereIn("provinceCode", $data['provinceCodes']);
                        }
                        )->when(
                            $data['cityCodes'], function ($query) use ($data) {
                            $query->orWhereIn("cityCode", $data['cityCodes']);
                        }
                        )->when(
                            $data['areaCodes'], function ($query) use ($data) {
                            $query->orWhereIn("areaCode", $data['areaCodes']);
                        }
                        );
                    }
                );
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->whereIn('developConsultantId', $data['userIds'])
                            ->orWhereIn('createdByUid', $data['userIds']);
                    }
                );
            }
            )
            ->count();

        if ($isOperate) {
            // 赤瞳,省总   房源审批
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_PROVINCE, UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER])) {
                return [
                    [
                        'type'     => self::TYPE_8,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_8] ?? '',
                        'count'    => $housePerfectCount,// 房源线索完善
                    ],
                    [
                        'type'     => self::TYPE_13,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_13] ?? '',
                        'count'    => $houseDistributeCount,   // 房源分配
                    ],
                    [
                        'type'     => self::TYPE_9,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_9] ?? '',
                        'count'    => $houseInApprovalCount,// 房源审批中
                    ],
                ];
            }
            // 大黄蜂   房源审批
            if (in_array($data['role'], [UserRoleService::ROLE_SPECIAL_1])) {
                return [
                    [
                        'type'     => self::TYPE_9,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_9] ?? '',
                        'count'    => $houseInApprovalCount,// 房源审批中
                    ],
                ];
            }
            if (in_array($data['role'], [UserRoleService::ROLE_SPECIAL_2])) {
                return [
                    [
                        'type'     => self::TYPE_8,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_8] ?? '',
                        'count'    => $housePerfectCount,// 房源线索完善
                    ],
                    [
                        'type'     => self::TYPE_9,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_9] ?? '',
                        'count'    => $houseInApprovalCount,// 房源审批中
                    ],
                ];
            }
            // 选址开发  提交房源（含房源线索完善、房源选址评估、房源修改）
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT, UserRoleService::ROLE_BASE_KAM])) {
                return [
                    [
                        'type'     => self::TYPE_8,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_8] ?? '',
                        'count'    => $housePerfectCount,// 房源线索完善
                    ],
                    [
                        'type'     => self::TYPE_10,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_10] ?? '',
                        'count'    => $houseModifyCount,// 房源待修改
                    ],
                ];
            }
        } elseif (in_array($data['role'], [UserRoleService::ROLE_BASE_PROVINCE, UserRoleService::ROLE_SPECIAL_2, UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER])) {
            return [
                [
                    'type'     => self::TYPE_8,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_8] ?? '',
                    'count'    => $housePerfectCount,// 房源线索完善
                ],
                [
                    'type'     => self::TYPE_13,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_13] ?? '',
                    'count'    => $houseDistributeCount,   // 房源分配
                ],
                [
                    'type'     => self::TYPE_9,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_9] ?? '',
                    'count'    => $houseInApprovalCount,// 房源审批中
                ],
                [
                    'type'     => self::TYPE_10,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_10] ?? '',
                    'count'    => $houseModifyCount,// 房源待修改
                ],
                [
                    'type'     => self::TYPE_12,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_12] ?? '',
                    'count'    => $houseUseCount,// 待使用房源
                ],
            ];
        }
        return [
            [
                'type'     => self::TYPE_8,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_8] ?? '',
                'count'    => $housePerfectCount,// 房源线索完善
            ],
            [
                'type'     => self::TYPE_9,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_9] ?? '',
                'count'    => $houseInApprovalCount,// 房源审批中
            ],
            [
                'type'     => self::TYPE_10,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_10] ?? '',
                'count'    => $houseModifyCount,// 房源待修改
            ],
            [
                'type'     => self::TYPE_12,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_12] ?? '',
                'count'    => $houseUseCount,// 待使用房源
            ],
        ];

    }

    /**
     * 勘址
     * @param array $data
     * @param int $isOperate 0-全部 1-待我处理
     * @param int $isRel
     * @return array
     */
    public static function countSiteSurvey(array $data, int $isOperate, int $isRel = 0): array
    {
        if ($isOperate || $isRel) {
            $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
        }
        if ($data['search']['provinceCodes']) {
            $data['provinceCodes'] = $data['search']['provinceCodes'];
        }
        if ($data['search']['cityCodes']) {
            $data['cityCodes'] = $data['search']['cityCodes'];
        }
        if ($data['search']['areaCodes']) {
            $data['areaCodes'] = $data['search']['areaCodes'];
        }
        $siteSurveySql = CustomerDepartmentTaskModel::query()
            ->when(
                !$data['search']['fyName'] && $data['orderNos'], function ($query) use ($data) {
                $query->where('wgNumber', $data['orderNos']);
            }
            )
            ->when(
                $data['search']['fyName'], function ($query) use ($data) {
                //区分编号与地址搜索
                if (strpos($data['search']['fyName'], 'sc') !== false ||
                    strpos($data['search']['fyName'], 'SC') !== false ||
                    strpos($data['search']['fyName'], 'Sc') !== false ||
                    strpos($data['search']['fyName'], 'sC') !== false ||
                    is_numeric($data['search']['fyName'])) {
                    $query->where('wgNumber', $data['search']['fyName']);
                } else {
                    $query->where(
                        function ($query) use ($data) {
                            $query->orWhere('wgName', 'like', "%{$data['search']['fyName']}%")
                                ->orWhere('prefixAddress', 'like', "%{$data['search']['fyName']}%");
                        }
                    );
                }
            }
            )
            ->when(
                $data['provinceCodes'] || $data['cityCodes'] || $data['areaCodes'], function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->when(
                            $data['provinceCodes'], function ($query) use ($data) {
                            $query->whereIn("provinceCode", $data['provinceCodes']);
                        }
                        )->when(
                            $data['cityCodes'], function ($query) use ($data) {
                            $query->whereIn("cityCode", $data['cityCodes']);
                        }
                        )->when(
                            $data['areaCodes'], function ($query) use ($data) {
                            $query->whereIn("districtCode", $data['areaCodes']);
                        }
                        );
                    }
                );
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->whereIn('assignId', $data['userIds']);
            }
            )
            ->when(
                $data['search']['grade'], function ($query) use ($data) {
                $query->whereIn('grade', $data['search']['grade']);
            }
            )
            ->groupBy('projectPhase')
            ->selectRaw('projectPhase,count(1) num')
            ->get();

        // 待跟进
        $toBeFollowedUpCount = $siteSurveySql
            ->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_WAIT_FOLLOW_UP])
            ->sum('num');

        // 无线索
        $noClueCount = $siteSurveySql
            ->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_NO_CLUE])
            ->sum('num');

        // 有效线索
        $effectiveClueCount = $siteSurveySql
            ->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE])
            ->sum('num');

        // 有效房源
        $effectiveHouseCount = $siteSurveySql
            ->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE])
            ->sum('num');

        // 已确址
        $siteLocationCount = $siteSurveySql
            ->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION])
            ->sum('num');

        // 已完成
        $siteConfirmCount = $siteSurveySql
            ->whereIn('projectPhase', [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM])
            ->sum('num');

        if ($isOperate) {
            // 大客户经理
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_KAM])) {
                return [
                    [
                        'type'     => self::TYPE_29,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_29] ?? '',
                        'count'    => $toBeFollowedUpCount,// 待跟进
                    ],
                    [
                        'type'     => self::TYPE_30,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_30] ?? '',
                        'count'    => $noClueCount,   // 无线索
                    ],
                    [
                        'type'     => self::TYPE_31,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_31] ?? '',
                        'count'    => $effectiveClueCount,// 有效线索
                    ],
                    [
                        'type'     => self::TYPE_32,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_32] ?? '',
                        'count'    => $effectiveHouseCount,// 有效房源
                    ],
                    [
                        'type'     => self::TYPE_33,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_33] ?? '',
                        'count'    => $siteLocationCount,   // 已确址
                    ],
                    [
                        'type'     => self::TYPE_34,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_34] ?? '',
                        'count'    => $siteConfirmCount,// 已完成
                    ],
                ];
            }
        } elseif (in_array($data['role'], [UserRoleService::ROLE_BASE_KAM, UserRoleService::ROLE_SPECIAL_1, UserRoleService::ROLE_SPECIAL_2])) {
            return [
                [
                    'type'     => self::TYPE_29,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_29] ?? '',
                    'count'    => $toBeFollowedUpCount,// 待跟进
                ],
                [
                    'type'     => self::TYPE_30,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_30] ?? '',
                    'count'    => $noClueCount,   // 无线索
                ],
                [
                    'type'     => self::TYPE_31,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_31] ?? '',
                    'count'    => $effectiveClueCount,// 有效线索
                ],
                [
                    'type'     => self::TYPE_32,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_32] ?? '',
                    'count'    => $effectiveHouseCount,// 有效房源
                ],
                [
                    'type'     => self::TYPE_33,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_33] ?? '',
                    'count'    => $siteLocationCount,   // 已确址
                ],
                [
                    'type'     => self::TYPE_34,
                    'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_34] ?? '',
                    'count'    => $siteConfirmCount,// 已完成
                ],
            ];
        }
        return [];
    }

    /**
     * 筹备
     * @param array $data
     * @param int $isOperate 0-全部 1-待我处理
     * @param int $isRel
     * @return array
     */
    public static function countPrepare(array $data, int $isOperate, int $isRel = 0): array
    {
        $getOrderNos = self::searchWhereByFyName($data['search']);
        if ($getOrderNos) {
            $data['orderNos'] = array_unique(array_merge($data['orderNos'], $getOrderNos));
        }
        $child = self::getOrderNosByProvinceCode($data);
        if ($isOperate || $isRel) {
            $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
        }
        $prepareOrderSql = OpenShopSiteMissionModel::query()
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('orderNo', $data['orderNos']);
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->whereIn('dealUid', $data['userIds']);
            }
            )
            ->when(
                $child, function ($query) use ($child) {
                $query->whereRaw('orderNo in (' . BaseModel::toSqlWithParam($child) . ')');
            }
            )
            ->where('isShow', 1)
            ->where('orderStatus', 1)
            ->groupBy(['stepStatus', 'status'])
            ->selectRaw('stepStatus,status,count(1) num')
            ->get();

        // 确认建店信息（填写督导）
        $confirmSupervisorCount = $prepareOrderSql
            ->where('status', SiteMissionEnum::STATUS_1)
            ->whereIn('stepStatus', [MissionTemplateEnum::STEP_STATUS_6])
            ->sum('num');

        // 确认施工进场
        $confirmConstructionCount = $prepareOrderSql
            ->where('status', SiteMissionEnum::STATUS_1)
            ->whereIn('stepStatus', [MissionTemplateEnum::STEP_STATUS_9])
            ->sum('num');

        // 确认施工完成
        $confirmConstructionCompleteCount = $prepareOrderSql
            ->where('status', SiteMissionEnum::STATUS_1)
            ->whereIn('stepStatus', [MissionTemplateEnum::STEP_STATUS_10])
            ->sum('num');

        // 筹备完成-上面步骤完成状态
        $prepareCompleteCount = $prepareOrderSql
            ->where('status', SiteMissionEnum::STATUS_2)
            ->whereIn(
                'stepStatus', [
                    MissionTemplateEnum::STEP_STATUS_6, MissionTemplateEnum::STEP_STATUS_9,
                    MissionTemplateEnum::STEP_STATUS_10
                ]
            )
            ->sum('num');
        if ($isOperate) {
            // 筹备  1、确认建店信息（填写督导） 2、确认施工进场 3、确认施工完成
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_PREPARE])) {
                return [
                    [
                        'type'     => self::TYPE_15,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_15] ?? '',
                        'count'    => $confirmSupervisorCount,// 确认建店信息
                    ],
                    [
                        'type'     => self::TYPE_16,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_16] ?? '',
                        'count'    => $confirmConstructionCount,// 确认施工进场
                    ],
                    [
                        'type'     => self::TYPE_17,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_17] ?? '',
                        'count'    => $confirmConstructionCompleteCount,// 确认施工完成
                    ],
                ];
            }
        }
        return [
            [
                'type'     => self::TYPE_15,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_15] ?? '',
                'count'    => $confirmSupervisorCount,// 确认建店信息
            ],
            [
                'type'     => self::TYPE_16,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_16] ?? '',
                'count'    => $confirmConstructionCount,// 确认施工进场
            ],
            [
                'type'     => self::TYPE_17,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_17] ?? '',
                'count'    => $confirmConstructionCompleteCount,// 确认施工完成
            ],
            [
                'type'     => self::TYPE_18,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_18] ?? '',
                'count'    => $prepareCompleteCount,// 筹备完成
            ],
        ];

    }

    /**
     * 开店
     * @param array $data
     * @param int $isOperate 0-全部 1-待我处理
     * @param int $isRel 1-和自己关联（全部任务）
     * @return array
     */
    public static function countCruise(array $data, int $isOperate, int $isRel = 0): array
    {
        $getOrderNos = self::searchWhereByFyName($data['search']);
        if ($getOrderNos) {
            $data['orderNos'] = array_unique(array_merge($data['orderNos'], $getOrderNos));
        }
        $child = '';
        if (!in_array($data['role'], [UserRoleService::ROLE_BASE_SUPERVISOR])) {
            $child = self::getOrderNosByProvinceCode($data);
        }
        if (!$isOperate && !$data['allArea'] && in_array($data['role'], [UserRoleService::ROLE_BASE_SUPERVISOR])) {
            $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
        }
        $cruiseOrderSql = CruiseOrderModel::query()
            ->where('cruise_order.type', CruiseOrderModel::TYPE_NEW_SHOP_HELP)
            ->when(
                $isOperate, function ($query) use ($isOperate, $data) {
                $query->where('cruise_order.handlerId', $data['rmsUserId']);
            }
            )
            ->when(
                $child, function ($query) use ($child) {
                $query->whereRaw('cruise_order.orderNo in (' . BaseModel::toSqlWithParam($child) . ')');
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query
                    ->leftJoin('open_shop_main_process', 'open_shop_main_process.orderNo', '=', 'cruise_order.orderNo')
                    ->leftJoin('open_shop_order_manager', 'open_shop_order_manager.mainProcessId', '=', 'open_shop_main_process.id')
                    ->where('open_shop_order_manager.isDeleted', 0)
                    ->whereIn('open_shop_order_manager.managerUid', $data['userIds'])
                    ->where('open_shop_order_manager.type', OpenShopOrderManagerModel::MANAGER_TYPE_5);//督导
            }
            )
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('cruise_order.orderNo', $data['orderNos']);
            }
            )
            ->groupBy('cruise_order.status')
            ->selectRaw('cruise_order.status,count(1) num')
            ->get();

        // 提交开业报告
        $notSubmit = $cruiseOrderSql
            ->whereIn('status', [CruiseOrderModel::STATUS_NOT_SUBMIT])
            ->sum('num');

        // 开业报告审批中
        $notReview = $cruiseOrderSql
            ->whereIn('status', [CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_WAIT_MODIFY_EXT])
            ->sum('num');

        // 修改开业报告
        $notModify = $cruiseOrderSql
            ->whereIn('status', [CruiseOrderModel::STATUS_NOT_MODIFY])
            ->sum('num');

        // 已开业
        $completed = $cruiseOrderSql
            ->whereIn('status', [CruiseOrderModel::STATUS_COMPLETE])
            ->sum('num');
        if ($isOperate) {
            // 督导  提交开业报告 2、修改开业报告
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_SUPERVISOR])) {
                return [
                    [
                        'type'     => self::TYPE_20,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_20] ?? '',
                        'count'    => $notSubmit,// 提交开业报告
                    ],
                    [
                        'type'     => self::TYPE_22,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_22] ?? '',
                        'count'    => $notModify,// 修改开业报告
                    ],
                ];
            }
            // 辰月  审批开业报告
            if (in_array($data['role'], [UserRoleService::ROLE_SPECIAL_4])) {
                return [
                    [
                        'type'     => self::TYPE_21,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_21] ?? '',
                        'count'    => $notReview,// 开业报告审批中
                    ],
                ];
            }
        }
        return [
            [
                'type'     => self::TYPE_20,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_20] ?? '',
                'count'    => $notSubmit,// 提交开业报告
            ],
            [
                'type'     => self::TYPE_21,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_21] ?? '',
                'count'    => $notReview,// 开业报告审批中
            ],
            [
                'type'     => self::TYPE_22,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_22] ?? '',
                'count'    => $notModify,// 修改开业报告
            ],
            [
                'type'     => self::TYPE_23,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_23] ?? '',
                'count'    => $completed,// 已开业
            ],
        ];

    }


    /**
     * 新日常任务
     * @param array $data
     * @param int $isOperate 0-全部 1-待我处理
     * @param int $isRel 1-和自己关联（全部任务）
     * @return array
     */
    public static function countDaily(array $data, int $isOperate, int $isRel = 0): array
    {
        if ($isOperate || $isRel) {
            $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
        }

        // 搜索匹配
        $searchRes = ['shopIds' => []];
        if ($data['search']['fyName']) {
            $searchRes = self::searchWhereRmsShop($data['search']['fyName'], true);
        } elseif ($data['search']['shopName']) {
            $searchRes = self::searchWhereRmsShop($data['search']['shopName']);
        }

        $countDaily = TaskNodesModel::query()
            ->join('kms_task', 'kms_task.id', '=', 'kms_task_nodes.taskId')
            ->join('kms_daily_task_logs', 'kms_task.businessId', '=', 'kms_daily_task_logs.id')
            ->whereRaw("kms_task_nodes.id IN ( SELECT MAX( id ) FROM kms_task_nodes GROUP BY taskId ) ")
            ->when(
                in_array(
                    $data['role'], [
                        UserRoleService::ROLE_BASE_SUPERVISOR,
                    ]
                ), function ($query) use ($data) {
                $query->where('kms_daily_task_logs.handlerUserId', $data['rmsUserId']);
            }
            )
            ->when(
                $searchRes['shopIds'], function ($query) use ($searchRes) {
                $query->whereIn('kms_daily_task_logs.shopId', $searchRes['shopIds']);
            }
            )
            ->when(
                self::checkRolePermissions($data['role'], 3) && $data['userIds'], function ($query) use ($isOperate, $data) {
                $query->where(
                    function ($query) use ($isOperate, $data) {
                        $query->whereIn('handlerUserId', $data['userIds'])
                            ->when(
                                in_array(
                                    $data['role'], [
                                        UserRoleService::ROLE_BASE_PROVINCE,
                                        UserRoleService::ROLE_BASE_CITY_MANAGER,
                                        UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                                    ]
                                ) && $isOperate && $data['userIds'], function ($query) use ($data) {
                                $query->orWhereRaw("JSON_CONTAINS(approveUserIds, JSON_ARRAY(" . implode(',', $data['userIds']) . "))");
                            }
                            );
                    }
                );
            }
            )
            ->where('kms_task_nodes.isDeleted', 0)
            ->where('kms_task.isDeleted', 0)
            ->where('kms_daily_task_logs.isDeleted', 0)
            ->groupBy(["kms_task_nodes.businessType", "kms_task_nodes.isApprovalRejected"])
            ->selectRaw("kms_task_nodes.businessType,kms_task_nodes.isApprovalRejected,count(1) num")
            ->get();

        // 日常任务待提交
        $toBeSubmitted = $countDaily->where('businessType', TaskTemplateNodesModel::BUSINESS_TYPE_SUBMIT)
            ->where('isApprovalRejected', 0)->sum('num');

        // 日常任务审批中
        $inApproval = $countDaily->where('businessType', TaskTemplateNodesModel::BUSINESS_TYPE_APPROVE)
            ->where('isApprovalRejected', 0)->sum('num');

        // 日常任务已结束
        $end = $countDaily->where('businessType', TaskTemplateNodesModel::BUSINESS_TYPE_FINISHED)
            ->where('isApprovalRejected', 0)->sum('num');

        // 日常任务待修改
        $toBeModified = $countDaily->where('businessType', TaskTemplateNodesModel::BUSINESS_TYPE_SUBMIT)
            ->where('isApprovalRejected', 1)->sum('num');

        if ($isOperate) {
            // 省总,城市经理,督导  创建临时任务
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_PROVINCE, UserRoleService::ROLE_BASE_CITY_MANAGER])) {
                return [
                    [
                        'type'     => self::TYPE_27,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_27] ?? '',
                        'count'    => $inApproval,// 日常任务审批中
                    ],
                ];
            }
            if (in_array($data['role'], [UserRoleService::ROLE_BASE_SUPERVISOR])) {
                return [
                    [
                        'type'     => self::TYPE_25,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_25] ?? '',
                        'count'    => $toBeSubmitted,// 日常任务待提交
                    ],
                    [
                        'type'     => self::TYPE_26,
                        'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_26] ?? '',
                        'count'    => $toBeModified,// 日常任务待修改
                    ],
                ];
            }
        }
        return [
            [
                'type'     => self::TYPE_25,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_25] ?? '',
                'count'    => $toBeSubmitted,// 日常任务待提交
            ],
            [
                'type'     => self::TYPE_26,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_26] ?? '',
                'count'    => $toBeModified,// 日常任务待修改
            ],
            [
                'type'     => self::TYPE_27,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_27] ?? '',
                'count'    => $inApproval,// 日常任务审批中
            ],
            [
                'type'     => self::TYPE_28,
                'typeText' => self::TYPE_TEXT_MAPPING[self::TYPE_28] ?? '',
                'count'    => $end,// 日常任务已结束
            ],
        ];
    }


    /**
     * 任务总列表
     * @param int $rmsUserId
     * @param int $isOperate 0-全部 1-待我处理
     * @param array $types
     * @param array $userIds
     * @param int $pageNum
     * @param int $pageSize
     * @param array $search
     * @return array
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function getList(int $rmsUserId, int $isOperate, array $types, array $userIds, int $pageNum, int $pageSize, array $search): array
    {
        $getUserRole   = UserRoleService::getUserRole($rmsUserId);
        $role          = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        $roleDesc      = $getUserRole['desc'] ?? '';
        $provinceCodes = $getUserRole['userResponsibleArea']['area']['province'] ?? [];
        $cityCodes     = $getUserRole['userResponsibleArea']['area']['city'] ?? [];
        $areaCodes     = $getUserRole['userResponsibleArea']['area']['district'] ?? [];
        $allArea       = $getUserRole['userResponsibleArea']['all'] ?? false;

        $siteLocationWhere  = $houseWhere = $siteMissWhere = $cruiseWhere = $dailyWhere = $siteSurveyWhere = [];
        $isApprovalRejected = $siteMissFinish = 0;
        foreach ($types as $type) {
            switch ($type) {
                case self::TYPE_1:
                    $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_0, OpenShopSiteLocationModel::SITE_STATUS_1]);//提交选址
                    break;
                case self::TYPE_2:
                    $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_3]);//选址修改
                    break;
                case self::TYPE_3:
                    $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_4]);//完成落址
                    break;
                case self::TYPE_4:
                    $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_2, OpenShopSiteLocationModel::SITE_STATUS_10, OpenShopSiteLocationModel::SITE_STATUS_11]);//选址审批
                    break;
                case self::TYPE_5:
                    $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_21]);//合同上传
                    break;
                case self::TYPE_6:
                    $siteMissWhere = array_merge($siteMissWhere, [MissionTemplateEnum::STEP_STATUS_3]);          //开发待指派
                    break;
                case self::TYPE_7:
                    $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_20]);//商家待确认
                    break;

                case self::TYPE_8:
                    $houseWhere = array_merge($houseWhere, [OpenShopSiteLocationModel::CLUE_STATUS_12, OpenShopSiteLocationModel::CLUE_STATUS_2, OpenShopSiteLocationModel::CLUE_STATUS_13]);//房源线索完善
                    break;
                case self::TYPE_9:
                    $houseWhere = array_merge($houseWhere, [OpenShopSiteLocationModel::CLUE_STATUS_3, OpenShopSiteLocationModel::CLUE_STATUS_11]);//房源审批中
                    break;
                case self::TYPE_10:
                    $houseWhere = array_merge($houseWhere, [OpenShopSiteLocationModel::CLUE_STATUS_4]);//房源待修改
                    break;
                case self::TYPE_12:
                    $houseWhere = array_merge($houseWhere, [OpenShopSiteLocationModel::CLUE_STATUS_5]);//待使用房源
                    break;
                case self::TYPE_13:
                    $houseWhere = array_merge($houseWhere, [OpenShopSiteLocationModel::CLUE_STATUS_1]);//房源分配
                    break;

                case self::TYPE_15:
                    $siteMissWhere = array_merge($siteMissWhere, [MissionTemplateEnum::STEP_STATUS_6]);//确认建店信息
                    break;
                case self::TYPE_16:
                    $siteMissWhere = array_merge($siteMissWhere, [MissionTemplateEnum::STEP_STATUS_9]);//确认施工进场
                    break;
                case self::TYPE_17:
                    $siteMissWhere = array_merge($siteMissWhere, [MissionTemplateEnum::STEP_STATUS_10]);//确认施工完成
                    break;
                case self::TYPE_18:
                    $siteMissWhere  = array_merge(
                        $siteMissWhere, [
                            MissionTemplateEnum::STEP_STATUS_6, MissionTemplateEnum::STEP_STATUS_9,
                            MissionTemplateEnum::STEP_STATUS_10,
                        ]
                    );//筹备完成
                    $siteMissFinish = 1;
                    break;

                case self::TYPE_20:
                    $cruiseWhere = array_merge($cruiseWhere, [CruiseOrderModel::STATUS_NOT_SUBMIT]); //提交开业报告
                    break;
                case self::TYPE_21:
                    $cruiseWhere = array_merge($cruiseWhere, [CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_WAIT_MODIFY_EXT]);//开业报告审批中
                    break;
                case self::TYPE_22:
                    $cruiseWhere = array_merge($cruiseWhere, [CruiseOrderModel::STATUS_NOT_MODIFY]); //修改开业报告
                    break;
                case self::TYPE_23:
                    $cruiseWhere = array_merge($cruiseWhere, [CruiseOrderModel::STATUS_COMPLETE]);    //已开业
                    break;

                case self::TYPE_25:
                    $dailyWhere = array_merge($dailyWhere, [TaskTemplateNodesModel::BUSINESS_TYPE_SUBMIT]);//日常任务待提交
                    break;
                case self::TYPE_26:
                    $isApprovalRejected = 1;//日常任务待修改
                    break;
                case self::TYPE_27:
                    $dailyWhere = array_merge($dailyWhere, [TaskTemplateNodesModel::BUSINESS_TYPE_APPROVE]);//日常任务审批中
                    break;
                case self::TYPE_28:
                    $dailyWhere = array_merge($dailyWhere, [TaskTemplateNodesModel::BUSINESS_TYPE_FINISHED]);//日常任务已结束
                    break;

                case self::TYPE_29:
                    $siteSurveyWhere = array_merge($siteSurveyWhere, [CustomerDepartmentTaskModel::PROJECT_PHASE_WAIT_FOLLOW_UP]);//待跟进
                    break;
                case self::TYPE_30:
                    $siteSurveyWhere = array_merge($siteSurveyWhere, [CustomerDepartmentTaskModel::PROJECT_PHASE_NO_CLUE]);//无线索
                    break;
                case self::TYPE_31:
                    $siteSurveyWhere = array_merge($siteSurveyWhere, [CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_CLUE]);//有效线索
                    break;
                case self::TYPE_32:
                    $siteSurveyWhere = array_merge($siteSurveyWhere, [CustomerDepartmentTaskModel::PROJECT_PHASE_EFFECTIVE_HOUSE]);//有效房源
                    break;
                case self::TYPE_33:
                    $siteSurveyWhere = array_merge($siteSurveyWhere, [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_LOCATION]);//已确址
                    break;
                case self::TYPE_34:
                    $siteSurveyWhere = array_merge($siteSurveyWhere, [CustomerDepartmentTaskModel::PROJECT_PHASE_SITE_CONFIRM]);//已完成
                    break;

            }
        }
        // 模糊搜索
        $searchRes = self::searchWhereByName($search);

        if ($search['orderNo']) {
            $searchRes['orderNos'] = [$search['orderNo']];
        }

        $data = [
            'role'               => $role,
            'siteLocationWhere'  => $siteLocationWhere,
            'houseWhere'         => $houseWhere,
            'siteMissWhere'      => $siteMissWhere,
            'siteMissFinish'     => $siteMissFinish,
            'cruiseWhere'        => $cruiseWhere,
            'dailyWhere'         => $dailyWhere,
            'siteSurveyWhere'    => $siteSurveyWhere,
            'isApprovalRejected' => $isApprovalRejected,
            'userIds'            => array_unique(array_merge($userIds, $searchRes['rmsUserIds'])),
            'provinceCodes'      => $provinceCodes,
            'cityCodes'          => $cityCodes,
            'areaCodes'          => $areaCodes,
            'allArea'            => $allArea,
            'rmsUserId'          => $rmsUserId,
            'search'             => $search,
            'orderNos'           => $searchRes['orderNos'],
            'isOperate'          => $isOperate,
            'pageSize'           => $pageSize,
            'pageNum'            => $pageNum,
        ];

        // 选址
        if ($siteLocationWhere || ($siteMissWhere == [MissionTemplateEnum::STEP_STATUS_3])) {
            return self::getSiteLocationList($data);
        }

        // 房源
        if ($houseWhere) {
            return self::getSiteLocationHouseList($data);
        }

        // 勘址
        if ($siteSurveyWhere) {
            return self::getSiteSurveyWhereList($data);
        }

        // 筹备
        if ($siteMissWhere) {
            return self::getSiteMissionList($data);
        }

        // 增长
        if ($cruiseWhere) {
            return self::getCruiseList($data);
        }

        // 日常任务
        if ($dailyWhere || $isApprovalRejected) {
            return self::getDailyWhereList($data);
        }

        return [];
    }

    /**
     * 选址
     * @param array $data
     * @param bool $isTag
     * @return array
     * @throws GuzzleException
     */
    public static function getSiteLocationList(array $data, bool $isTag = false): array
    {
        $getOrderNos = self::searchWhereByFyName($data['search']);
        if ($getOrderNos) {
            $data['orderNos'] = array_unique(array_merge($data['orderNos'], $getOrderNos));
        }
        $orderNosBySiteMiss = [];
        if ($data['siteMissWhere']) {
            if (!count($data['siteLocationWhere'])) {// 只有开发待指派
                return self::getSiteMissionList($data);
            }
            $orderNosBySiteMiss = self::getOrderNosBySiteMiss($data);
        }
        if ($data['search']['orderNo']) {
            $orderNosBySiteMiss = [];
            $data['orderNos']   = [$data['search']['orderNo']];
        }
        $paginator = OpenShopSignOrderModel::query()
            ->leftJoin('open_shop_site_locations', 'open_shop_site_locations.orderNo', '=', 'open_shop_sign_order.orderNo')
            ->when(
                $isTag && $data['search']['tagIds'], function ($query) {
                $query->join('open_shop_order_tags_mapping', 'open_shop_order_tags_mapping.orderNo', '=', 'open_shop_site_locations.orderNo');
            }
            )
            ->when(
                $orderNosBySiteMiss, function ($query) use ($orderNosBySiteMiss) {
                $query->whereIn('open_shop_sign_order.orderNo', $orderNosBySiteMiss);// 开发待指派 不在选址表 需要融合数据
            }
            )
            ->orWhere(
                function ($query) use ($isTag, $data) {
                    $query
                        ->when(
                            $isTag && $data['search']['tagIds'], function ($query) use ($data) {
                            $query->whereIn("open_shop_order_tags_mapping.tagId", $data['search']['tagIds'])
                                ->where("open_shop_order_tags_mapping.isDeleted", 0);//筹备标签Id搜索
                        }
                        )
                        ->where('open_shop_site_locations.isDeleted', 0)
                        ->whereIn('open_shop_site_locations.source', [OpenShopSiteLocationModel::SOURCE_OPEN_SHOP])
                        ->when(
                            $data['orderNos'], function ($query) use ($data) {
                            $query->whereIn('open_shop_site_locations.orderNo', $data['orderNos']);
                        }
                        )
                        ->when(
                            !in_array(
                                $data['role'], [
                                    UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT,
                                ]
                            ) && ($data['provinceCodes'] || $data['cityCodes'] || $data['areaCodes']), function ($query) use ($data) {
                            $query->where(
                                function ($query) use ($data) {
                                    $query->when(
                                        $data['provinceCodes'], function ($query) use ($data) {
                                        $query->whereIn("open_shop_site_locations.provinceCode", $data['provinceCodes']);
                                    }
                                    )->when(
                                        $data['cityCodes'], function ($query) use ($data) {
                                        $query->orWhereIn("open_shop_site_locations.cityCode", $data['cityCodes']);
                                    }
                                    )->when(
                                        $data['areaCodes'], function ($query) use ($data) {
                                        $query->orWhereIn("open_shop_site_locations.areaCode", $data['areaCodes']);
                                    }
                                    );
                                }
                            );
                        }
                        )
                        ->when(
                            $data['siteLocationWhere'], function ($query) use ($data) {
                            $query->whereIn('open_shop_site_locations.siteStatus', $data['siteLocationWhere']);
                        }
                        )
                        ->when(
                            $data['userIds'], function ($query) use ($data) {
                            $query->whereIn('open_shop_site_locations.developConsultantId', $data['userIds']);
                        }
                        )
                        ->when(
                            $data['isOperate'] || in_array($data['role'], [UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT, UserRoleService::ROLE_BASE_KAM]), function ($query) use ($data) {
                            $query->where(
                                function ($query) use ($data) {
                                    $query->where('open_shop_site_locations.developConsultantId', $data['rmsUserId'])
                                        ->orWhere(
                                            function ($query) use ($data) {
                                                $query->when(
                                                    in_array(
                                                        $data['role'], [
                                                            UserRoleService::ROLE_BASE_PROVINCE,
                                                            UserRoleService::ROLE_SPECIAL_1,
                                                            UserRoleService::ROLE_SPECIAL_2,
                                                            UserRoleService::ROLE_SPECIAL_3,
                                                            UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                                                        ]
                                                    ), function ($query) use ($data) {
                                                    $query->whereRaw("FIND_IN_SET({$data['rmsUserId']}, `open_shop_site_locations`.`handler`) != 0");//现阶段处理人Id 省总和赤瞳
                                                }
                                                );
                                            }
                                        );
                                }
                            );
                        }
                        );
                }
            )
            ->orderByDesc('open_shop_site_locations.updatedAt')
            ->with(
                [
                    'identityCardRel',
                    'baseInfoRel',
                ]
            )
            ->select(["open_shop_site_locations.*", "open_shop_sign_order.shopCode", "open_shop_sign_order.orderNo as orderNos"])
            ->offset($data['pageNum'])
            ->limit($data['pageSize'])
            ->get();
//            ->paginate($data['pageSize'], ["open_shop_site_locations.*", "open_shop_sign_order.shopCode", "open_shop_sign_order.orderNo as orderNos"], 'pageNum', $data['pageNum']);

        $getSiteMissionList = [];
        $orderNos           = $paginator->where('id', 0)->pluck('orderNos')->toArray();
        if ($orderNosBySiteMiss && $orderNos) {// 获取原开店-开发待指派开发任务
            $data['orderNos']        = $orderNos;
            $data['pageSize']        = count($data['orderNos']);
            $data['pageNum']         = 1;
            $data['isSiteLocations'] = 1;
            $getSiteMissionList      = self::getSiteMissionList($data)['list'] ?? [];
            $getSiteMissionList      = collect($getSiteMissionList)->keyBy('orderNo')->toArray();
        }

        //获取创建人
        $userList = RmsUserService::getRmsUserInfoByUserIds($paginator->pluck('createdByUid')->toArray());

        $rmsUserIds = $userList['data'] ?: [];

        //获得每个人的入职时间
        $joinTime = KmsUser::query()
            ->whereIn('rmsUserId', array_column($rmsUserIds, 'id'))
            ->where('isExited', KmsUser::IS_EXITED_OFF)
            ->pluck('joinTime', 'rmsUserId')
            ->toArray();

        //提交日志
        $submitModel = OpenShopSiteLocationExamineLogModel::query()
            ->whereIn('createdByUid', array_column($rmsUserIds, 'id'))
            ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_SITE_FROM_SUBMIT)
            ->withoutGlobalScope('isDel');
        //获得首次提交的订单
        $submitOrderNo = $submitModel->groupBy('createdByUid')
            ->pluck('orderNo')
            ->toArray();

        //获得首次提交的人
        $submitTempCount = [];
        $submitModel->each(
            function (OpenShopSiteLocationExamineLogModel $openShopSiteLocationExamineLogModel) use (&$submitTempCount) {
                $submitTempCount[] = $openShopSiteLocationExamineLogModel->createdByUid;
            }
        );
        $submitOnlyOneCount = [];
        $tempSubmit         = array_count_values($submitTempCount);
        foreach ($tempSubmit as $userId => $count) {
            if ($count == 1) {
                $submitOnlyOneCount[] = $userId;
            }
        }

        $list = $paginator->map(
            function ($item) use ($userList, $joinTime, $submitOrderNo, $submitOnlyOneCount, $getSiteMissionList) {
                if (isset($getSiteMissionList[$item->orderNos])) {
                    return $getSiteMissionList[$item->orderNos];
                }
                //判断任务类型
                if ($item->source == OpenShopSiteLocationModel::SOURCE_HOUSING && $item->bindId == OpenShopSiteLocationModel::SITE_LOCATION_BIND_FALSE) {
                    $info = '';
                    foreach (($userList['data'] ?? []) as $user) {
                        if ($user['id'] == $item->createdByUid) {
                            $info = $user['username'];
                        }
                    }
                    $siteOrClue = 1;
                    $cityArea   = $item->cityArea;
                    $statusText = OpenShopSiteLocationModel::SITE_LOCATION_CLUE_MAPPING[$item->clueStatus];
                    $status     = $item->clueStatus;
                    $number     = $item->orderNo; //编号
                } else {
                    $siteOrClue = 0;
                    $info       = (optional($item->identityCardRel)->name ?: '-') . ' ' . ($item->shopCode ?: '-');
                    $cityArea   = $item->cityArea ?: (optional($item->baseInfoRel)->chooseShopAddressPrefix ?: '-');
                    $statusText = OpenShopSiteLocationModel::CN_PROVINCE_STATUS[$item->siteStatus] ?? '-';
                    $status     = $item->siteStatus;
                    $number     = $item->shopCode ?: '-'; //编号
                }
                $tag = '';

                if (in_array(
                        $item->siteStatus,
                        [
                            OpenShopSiteLocationModel::SITE_STATUS_2,
                            OpenShopSiteLocationModel::SITE_STATUS_3,
                            OpenShopSiteLocationModel::SITE_STATUS_4,
                            OpenShopSiteLocationModel::SITE_STATUS_10,
                            OpenShopSiteLocationModel::SITE_STATUS_11,
                            OpenShopSiteLocationModel::SITE_STATUS_20,
                            OpenShopSiteLocationModel::SITE_STATUS_21,
                        ]
                    ) || in_array(
                        $item->clueStatus,
                        [
                            OpenShopSiteLocationModel::CLUE_STATUS_3,
                            OpenShopSiteLocationModel::CLUE_STATUS_4,
                            OpenShopSiteLocationModel::CLUE_STATUS_5,
                            OpenShopSiteLocationModel::CLUE_STATUS_6,
                            OpenShopSiteLocationModel::CLUE_STATUS_10,
                            OpenShopSiteLocationModel::CLUE_STATUS_11,
                            OpenShopSiteLocationModel::CLUE_STATUS_13,
                        ]
                    )) {
                    if (time() < (($joinTime[$item->developConsultantId] ?? 0) + 86400 * 60)) {
                        $tag = '新人提交';
                    }

                    if (in_array($item->orderNo, $submitOrderNo) && in_array($item->developConsultantId, $submitOnlyOneCount)) {
                        $tag = '首次提交';
                    }
                }

                return [
                    'id'                    => $item->id,
                    'orderNo'               => $item->orderNo,
                    'statusText'            => $statusText,
                    'status'                => $status,
                    'cityArea'              => $cityArea,
                    'info'                  => $info,
                    'tag'                   => $tag,
                    'updatedAt'             => $item->updatedAt ? date('Y-m-d H:i:s', $item->updatedAt->timestamp) : '-',
                    'siteOrClue'            => $siteOrClue,
                    'number'                => $number,
                    'developConsultantName' => $item->developConsultantName ?: '待指派开发顾问',
                    'messageFrom'           => $item->messageFrom,
                    "messageFromText"       => (function ($messageFrom) {
                        $messageFromText = "";
                        switch ($messageFrom) {
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_1:
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_3:
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_7:
                                $messageFromText = "自带址";
                                break;
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_2:
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_6:
                                $messageFromText = "推荐址";
                                break;
                            case SiteLocationEnum::MESSAGE_FROM_TYPE_5:
                                $messageFromText = "转让";
                                break;
                        }
                        return $messageFromText;
                    })(
                        $item->messageFrom
                    ),
                    'tags'                  => collect(OrderService::getOrderTags(1, SiteLocationService::tagLocationStatus($item)))
                        ->where('name', '迁')->values(),
                    'originSource'          => self::SOURCE_1,
                    'originSourceText'      => self::SOURCE_TEXT_MAPPING[self::SOURCE_1] ?? '',
                ];
            }
        );

        return [
            'list'     => $list,
            'count'    => 0,
            'pageNum'  => $data['pageNum'],
            'pageSize' => $data['pageSize'],
        ];
    }

    /**
     * 房源
     * @param array $data
     * @return array
     * @throws GuzzleException
     */
    public static function getSiteLocationHouseList(array $data): array
    {
        $paginator = OpenShopSiteLocationModel::query()
            ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_HOUSING])
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('orderNo', $data['orderNos']);
            }
            )
            ->when(
                $data['search']['fyName'], function ($query) use ($data) {
                //区分编号与地址搜索
                if (strpos($data['search']['fyName'], 'fy') !== false ||
                    strpos($data['search']['fyName'], 'FY') !== false ||
                    strpos($data['search']['fyName'], 'Fy') !== false ||
                    strpos($data['search']['fyName'], 'fY') !== false ||
                    is_numeric($data['search']['fyName'])) {
                    $query->where('orderNo', $data['search']['fyName']);
                } else {
                    $query->where(
                        function ($query) use ($data) {
                            $query->orWhere('address', 'like', "%{$data['search']['fyName']}%")
                                ->orWhere('siteAddress', 'like', "%{$data['search']['fyName']}%")
                                ->orWhere('cityArea', 'like', "%{$data['search']['fyName']}%");
                        }
                    );
                }
            }
            )
            ->when(
                !in_array(
                    $data['role'], [
                        UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT,
                    ]
                ) && ($data['provinceCodes'] || $data['cityCodes'] || $data['areaCodes']), function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->when(
                            $data['provinceCodes'], function ($query) use ($data) {
                            $query->whereIn("provinceCode", $data['provinceCodes']);
                        }
                        )->when(
                            $data['cityCodes'], function ($query) use ($data) {
                            $query->orWhereIn("cityCode", $data['cityCodes']);
                        }
                        )->when(
                            $data['areaCodes'], function ($query) use ($data) {
                            $query->orWhereIn("areaCode", $data['areaCodes']);
                        }
                        );
                    }
                );
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->whereIn('developConsultantId', $data['userIds'])
                            ->orWhereIn('createdByUid', $data['userIds']);
                    }
                );
            }
            )
            ->when(
                in_array(
                    $data['role'], [
                        UserRoleService::ROLE_BASE_PROVINCE,
                        UserRoleService::ROLE_SPECIAL_1,
                        UserRoleService::ROLE_SPECIAL_2,
                        UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                    ]
                ), function ($query) use ($data) {// 线索待分配(没有处理人) -- 省总分派
                $query->when(
                    $data['houseWhere'] == [OpenShopSiteLocationModel::CLUE_STATUS_1], function ($query) use ($data) {
                    $query->whereIn('clueStatus', $data['houseWhere']);
                }
                )->when(
                    !in_array(OpenShopSiteLocationModel::CLUE_STATUS_1, $data['houseWhere']), function ($query) use ($data) {
                    $query->whereIn('clueStatus', $data['houseWhere'])
                        ->when(
                            $data['isOperate'], function ($query) use ($data) {
                            $query->where(
                                function ($query) use ($data) {
                                    $query->where('developConsultantId', $data['rmsUserId'])
                                        ->orWhereRaw("FIND_IN_SET({$data['rmsUserId']}, `handler`) != 0");//现阶段处理人Id 省总和赤瞳
                                }
                            );
                        }
                        );
                }
                )->when(
                    in_array(OpenShopSiteLocationModel::CLUE_STATUS_1, $data['houseWhere']) && count($data['houseWhere']) > 1, function ($query) use ($data) {
                    $query->where(
                        function ($query) use ($data) {
                            $query->whereIn('clueStatus', $data['houseWhere'])
                                ->when(
                                    $data['isOperate'], function ($query) use ($data) {
                                    $query->where(
                                        function ($query) use ($data) {
                                            $query->where('developConsultantId', $data['rmsUserId'])
                                                ->orWhereRaw("FIND_IN_SET({$data['rmsUserId']}, `handler`) != 0");//现阶段处理人Id 省总和赤瞳
                                        }
                                    );
                                }
                                );
                        }
                    )->orWhereIn('clueStatus', [OpenShopSiteLocationModel::CLUE_STATUS_1]);
                }
                );
            }
            )
            ->when(
                !in_array(
                    $data['role'], [
                        UserRoleService::ROLE_BASE_PROVINCE,
                        UserRoleService::ROLE_SPECIAL_1,
                        UserRoleService::ROLE_SPECIAL_2,
                        UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                    ]
                ), function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->whereIn('clueStatus', $data['houseWhere'])
                            ->when(
                                $data['isOperate'] || in_array($data['role'], [UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT, UserRoleService::ROLE_BASE_KAM]), function ($query) use ($data) {
                                $query->where(
                                    function ($query) use ($data) {
                                        $query->where('developConsultantId', $data['rmsUserId']);
                                    }
                                );
                            }
                            );
                    }
                );
            }
            )
            ->orderByDesc('updatedAt')
            ->with(['uploadFileResourceRel'])
            ->select(['*'])
            ->offset($data['pageNum'])
            ->limit($data['pageSize'])
            ->get();
//            ->paginate($data['pageSize'], ['*'], 'pageNum', $data['pageNum']);

        $body = RmsUserService::getRmsUserInfoByUserIds($paginator->pluck('createdByUid')->toArray());
        $list = $paginator->map(
            function ($item) use (&$clueCount, &$putCount, &$successCount, $body) {
                if ($item->uploadFileResourceRel->toArray()) {
                    $image = $item->uploadFileResourceRel[0]->formatUrl ?? '';
                    foreach ($item->uploadFileResourceRel as $value) {
                        if ($value->position == UploadFileResourceEnum::SHOP_ADDRESS_FRONT_PHOTO) {
                            $image = $value->formatUrl;
                        }
                    }
                } else {
                    $image = 'https://file.51kuafu.com/52/42/6f191617b85d80427702dcf6e938872fa6bbb4552898631ca5a13787bdab.png'; //添加默认图片
                }
                $cityAreaArr = explode('-', $item->cityArea);
                if (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1]) && isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2])) {
                    $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1] . '-' . $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2];
                } elseif (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1])) {
                    $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1];
                } elseif (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2])) {
                    $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2];
                } else {
                    $cityArea = '';
                }
                $owner = '-';
                foreach (($body['data'] ?? []) as $user) {
                    if ($user['id'] == $item->createdByUid) {
                        $owner = $user['username'];
                    }
                }
                return [
                    'id'               => $item->id,
                    'orderNo'          => $item->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_6 ? 'FY' . $item->id : $item->orderNo,
                    'image'            => $image,
                    'address'          => $item->address,
                    'cityArea'         => $cityArea,
                    'statusText'       => OpenShopSiteLocationModel::CLUE_STATUS_MAP[$item->clueStatus],
                    'clueStatus'       => $item->clueStatus,
                    'recommender'      => $owner,
                    'shopGrade'        => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$item->shopGrade] ?? '',
                    'putTime'          => $item->putAt ? date('Y-m-d H:i:s', $item->putAt) : '-',
                    'area'             => $item->area ? $item->area . '㎡' : '-',
                    'clueRentMonth'    => ceil($item->clueRent / 12),
                    'clueRentDay'      => ceil($item->clueRent / 365),
                    'number'           => $item->orderNo,
                    'originSource'     => self::SOURCE_2,
                    'originSourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_2] ?? '',
                ];
            }
        );
        return [
            'list'     => $list,
            'count'    => 0,
            'pageNum'  => $data['pageNum'],
            'pageSize' => $data['pageSize'],
        ];
    }

    /**
     * 勘址
     * @param array $data
     * @return array
     */
    public static function getSiteSurveyWhereList(array $data): array
    {
        if ($data['isOperate'] || in_array($data['role'], [UserRoleService::ROLE_BASE_KAM])) {
            $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
        }
        if ($data['search']['provinceCodes']) {
            $data['provinceCodes'] = $data['search']['provinceCodes'];
        }
        if ($data['search']['cityCodes']) {
            $data['cityCodes'] = $data['search']['cityCodes'];
        }
        if ($data['search']['areaCodes']) {
            $data['areaCodes'] = $data['search']['areaCodes'];
        }
        $orderByField = 'id';
        if ($data['search']['sort']) {
            $orderByField = $data['search']['sort'];
        }
        $paginator = CustomerDepartmentTaskModel::query()
            ->when(
                !$data['search']['fyName'] && $data['orderNos'], function ($query) use ($data) {
                $query->where('wgNumber', $data['orderNos']);
            }
            )
            ->when(
                $data['search']['fyName'], function ($query) use ($data) {
                //区分编号与地址搜索
                if (strpos($data['search']['fyName'], 'sc') !== false ||
                    strpos($data['search']['fyName'], 'SC') !== false ||
                    strpos($data['search']['fyName'], 'Sc') !== false ||
                    strpos($data['search']['fyName'], 'sC') !== false ||
                    is_numeric($data['search']['fyName'])) {
                    $query->where('wgNumber', $data['search']['fyName']);
                } else {
                    $query->where(
                        function ($query) use ($data) {
                            $query->orWhere('wgName', 'like', "%{$data['search']['fyName']}%")
                                ->orWhere('prefixAddress', 'like', "%{$data['search']['fyName']}%");
                        }
                    );
                }
            }
            )
            ->when(
                $data['provinceCodes'] || $data['cityCodes'] || $data['areaCodes'], function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->when(
                            $data['provinceCodes'], function ($query) use ($data) {
                            $query->whereIn("provinceCode", $data['provinceCodes']);
                        }
                        )->when(
                            $data['cityCodes'], function ($query) use ($data) {
                            $query->whereIn("cityCode", $data['cityCodes']);
                        }
                        )->when(
                            $data['areaCodes'], function ($query) use ($data) {
                            $query->whereIn("districtCode", $data['areaCodes']);
                        }
                        );
                    }
                );
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->whereIn('assignId', $data['userIds']);
            }
            )
            ->when(
                $data['siteSurveyWhere'], function ($query) use ($data) {
                $query->whereIn('projectPhase', $data['siteSurveyWhere']);
            }
            )
            ->when(
                $data['search']['grade'], function ($query) use ($data) {
                $query->whereIn('grade', $data['search']['grade']);
            }
            )
            ->when(
                $data['search']['collect'], function ($query) use ($data) {
                $query->where('collect', $data['search']['collect']);
            }
            )
            ->orderByDesc($orderByField)
            ->select(['*'])
            ->offset($data['pageNum'])
            ->limit($data['pageSize'])
            ->get();
//            ->paginate($data['pageSize'], ['*'], 'pageNum', $data['pageNum']);

        //获取创建人
        $userList = RmsUserService::getRmsUserInfoByUserIds($paginator->pluck('assignId')->toArray());
        $userList = collect($userList['data'] ?: [])->keyBy('id')->toArray();

        $list = $paginator->map(
            function ($item) use ($userList) {
                return [
                    'id'               => $item->id,
                    'wgNumber'         => $item->wgNumber,
                    'wgType'           => $item->wgType,
                    'wgTypeText'       => CustomerDepartmentTaskModel::WG_TYPE_STR_MAPPING[$item->wgType],
                    'wgName'           => $item->wgName,
                    'assignId'         => $item->assignId,
                    'assignTime'       => $item->assignTime ? date('Y-m-d H:i:s', $item->assignTime) : '-',
                    'updatedAt'        => $item->updatedAt->toDateTimeString(),
                    'projectPhase'     => $item->projectPhase,
                    'projectPhaseText' => CustomerDepartmentTaskModel::PROJECT_PHASE_MAPPING[$item->projectPhase],
                    'grade'            => $item->grade,
                    'gradeText'        => CustomerDepartmentTaskModel::GRADE_MAPPING[$item->grade],
                    'collect'          => $item->collect,
                    'collectText'      => CustomerDepartmentTaskModel::COLLECT_MAPPING[$item->collect],
                    'prefixAddress'    => $item->prefixAddress,
                    'address'          => $item->address,
                    'assignUserName'   => $userList[$item->assignId]['username'] ?? '',
                    'originSource'     => self::SOURCE_7,
                    'originSourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_7] ?? '',
                ];
            }
        );
        return [
            'list'     => $list,
            'count'    => 0,
            'pageNum'  => $data['pageNum'],
            'pageSize' => $data['pageSize'],
        ];
    }


    /**
     * 增长
     * @param array $data
     * @return array
     * @throws GuzzleException
     */
    public static function getCruiseList(array $data): array
    {
        $getOrderNos = self::searchWhereByFyName($data['search']);
        if ($getOrderNos) {
            $data['orderNos'] = array_unique(array_merge($data['orderNos'], $getOrderNos));
        }
        $child = '';
        if (!in_array($data['role'], [UserRoleService::ROLE_BASE_SUPERVISOR])) {
            $child = self::getOrderNosByProvinceCode($data);
        }
        if (!$data['isOperate'] && !$data['allArea'] && in_array($data['role'], [UserRoleService::ROLE_BASE_SUPERVISOR])) {// 关联督导
            $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
        }
        if ($data['search']['orderNo']) {
            $data['orderNos'] = [$data['search']['orderNo']];
        }
        $paginator = CruiseOrderModel::query()
            ->with(['userIdentityCardRel', 'siteLocationRel', 'checkTaskDetailRel'])
            ->where('cruise_order.type', CruiseOrderModel::TYPE_NEW_SHOP_HELP)
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('cruise_order.orderNo', $data['orderNos']);
            }
            )
            ->when(
                $child, function ($query) use ($child) {
                $query->whereRaw('cruise_order.orderNo in (' . BaseModel::toSqlWithParam($child) . ')');
            }
            )
            ->when(
                $data['isOperate'], function ($query) use ($data) {
                $query->where('cruise_order.handlerId', $data['rmsUserId']);
            }
            )
            ->when(
                $data['cruiseWhere'], function ($query) use ($data) {
                $query->whereIn('cruise_order.status', $data['cruiseWhere']);
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query
                    ->leftJoin('open_shop_main_process', 'open_shop_main_process.orderNo', '=', 'cruise_order.orderNo')
                    ->leftJoin('open_shop_order_manager', 'open_shop_order_manager.mainProcessId', '=', 'open_shop_main_process.id')
                    ->where('open_shop_order_manager.isDeleted', 0)
                    ->whereIn('open_shop_order_manager.managerUid', $data['userIds'])
                    ->where('open_shop_order_manager.type', OpenShopOrderManagerModel::MANAGER_TYPE_5);//督导
            }
            )
            ->orderByDesc('cruise_order.updatedAt')
            ->select(['cruise_order.*'])
            ->offset($data['pageNum'])
            ->limit($data['pageSize'])
            ->get();
//            ->paginate($data['pageSize'], ['cruise_order.*'], 'pageNum', $data['pageNum']);

        $checkUserIds = [];
        $paginator->each(
            function (CruiseOrderModel $cruiseOrder) use (&$checkUserIds) {
                $checkUserIds[] = (int)optional($cruiseOrder->checkTaskDetailRel)->dealUid;
            }
        );

        //获取处理人
        $userInfo = RmsUserService::getRmsUserInfoByUserIds(array_merge($paginator->pluck('handlerId')->toArray(), $checkUserIds))['data'] ?? [];
        $userList = array_column($userInfo, 'username', 'id');

        $shopInfo = (new RmsShopApi())->getShopByIds($paginator->pluck('shopId')->toArray(), ['id', 'shopCode', 'name'])['data']['shopList'] ?? [];
        $shopList = array_column($shopInfo, null, 'id');

        $list = $paginator->map(
            function (CruiseOrderModel $cruiseOrder) use ($userList, $shopList) {
                //项目类型
                $sysTemplate = (int)optional($cruiseOrder->checkTaskDetailRel)->sysTemplate;
                if ($cruiseOrder->userIdentityCardRel->count()) {
                    $name = $cruiseOrder->userIdentityCardRel[0]->name;
                } else {
                    $name = '-';
                }

                return [
                    'id'               => $cruiseOrder->id,
                    'orderNo'          => $cruiseOrder->orderNo,
                    'shopId'           => $cruiseOrder->shopId,
                    'missionType'      => '新店帮扶',
                    'userName'         => $name,
                    'shopInfo'         => 'KF' . sprintf("%04d", ($shopList[$cruiseOrder->shopId]['shopCode'] ?? '0000')) . ' ' . ($shopList[$cruiseOrder->shopId]['name'] ?? '-'),
                    'shopArea'         => (string)optional($cruiseOrder->siteLocationRel)->cityArea ?: '-',
                    'updateTime'       => $cruiseOrder->updatedAt->toDateTimeString(),
                    'createTime'       => $cruiseOrder->createdAt->toDateTimeString(),
                    'status'           => $cruiseOrder->status,
                    'taskName'         => $cruiseOrder->getTaskName(),
                    'sysTemplate'      => $sysTemplate,
                    'taskType'         => CruiseTemplateModel::SYS_TEMPLATE_TEXT[$sysTemplate] ?? '-',
                    'statusText'       => CruiseOrderModel::CRUISE_STATUS_MAPPING[$cruiseOrder->status] ?? '未知任务状态',
                    'handler'          => $userList[$cruiseOrder->handlerId] ?? '未知处理人',
                    'checkUser'        => $userList[(int)optional($cruiseOrder->checkTaskDetailRel)->dealUid] ?? '-',
                    'checkId'          => (int)optional($cruiseOrder->checkTaskDetailRel)->id,
                    'originSource'     => self::SOURCE_4,
                    'originSourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_4] ?? '',
                ];
            }
        );
        return [
            'list'      => $list,
            'count'     => 0,
            'pageCount' => ceil($data['pageNum'] / $data['pageSize']),
            'pageNum'   => $data['pageNum'],
            'pageSize'  => $data['pageSize'],
        ];
    }

    /**
     * 开店-指派开发顾问，筹备确认施工完成，进场，建店
     * @param array $data
     * @return array
     * @throws GuzzleException
     */
    public static function getSiteMissionList(array $data): array
    {
        $status = 0;
        $child  = '';
        if (!isset($data['isSiteLocations'])) {
            $getOrderNos = self::searchWhereByFyName($data['search']);
            if ($getOrderNos) {
                $data['orderNos'] = array_unique(array_merge($data['orderNos'], $getOrderNos));
            }
            $child = self::getOrderNosByProvinceCode($data);
            if ($data['isOperate'] || in_array(
                    $data['role'], [
                        UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT,
                        UserRoleService::ROLE_BASE_PREPARE,
                    ]
                ) || (
                    in_array(
                        $data['role'], [
                            UserRoleService::ROLE_SPECIAL_2,
                            UserRoleService::ROLE_SPECIAL_5,
                            UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                        ]
                    ) && $data['isOperate'] && in_array(MissionTemplateEnum::STEP_STATUS_3, $data['siteMissWhere'])
                )) {
                $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
            }
            if ($data['siteMissFinish']) {
                if (count($data['siteMissWhere']) == count(
                        [
                            MissionTemplateEnum::STEP_STATUS_6,
                            MissionTemplateEnum::STEP_STATUS_9,
                            MissionTemplateEnum::STEP_STATUS_10,
                        ]
                    )) {
                    $status = SiteMissionEnum::STATUS_2;//已处理
                }
            } else {
                $status = SiteMissionEnum::STATUS_1;//未处理
            }
        }
        if ($data['search']['orderNo']) {
            $data['orderNos'] = [$data['search']['orderNo']];
        }

        $paginates = OpenShopSiteMissionModel::query()
            ->when(
                $status, function ($query) use ($status) {
                $query->where('status', $status);
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->whereIn('dealUid', $data['userIds']);
            }
            )
            ->when(
                $data['siteMissWhere'], function ($query) use ($data) {
                $query->whereIn('stepStatus', $data['siteMissWhere']);
            }
            )
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('orderNo', $data['orderNos']);
            }
            )
            ->when(
                $child, function ($query) use ($child) {
                $query->whereRaw('orderNo in (' . BaseModel::toSqlWithParam($child) . ')');
            }
            )
            ->where('isShow', 1)
            ->where('orderStatus', 1)
            ->with(['openShopUserIdentityCardRel', 'addressRel'])
            ->select(['*'])
            ->offset($data['pageNum'])
            ->limit($data['pageSize'])
            ->get();
//            ->paginate($data['pageSize'], ['*'], 'pageNum', $data['pageNum']);

        $dealUids      = $paginates->pluck('dealUid')->toArray();
        $dealUserInfos = collect(RmsUserService::getRmsUserInfoByUserIds($dealUids)['data'] ?? [])->keyBy('id');

        $lists = $paginates->map(
            function ($item) use ($dealUserInfos) {
                $dealUserInfo = $dealUserInfos[$item['dealUid']] ?? [];
                return [
                    'id'               => $item->id,
                    'orderNo'          => $item->orderNo,
                    'stepStatus'       => $item->stepStatus,
                    'missionName'      => $item->missionName,
                    'merchantName'     => (string)optional($item->openShopUserIdentityCardRel)->name,
                    'addressPrefix'    => (string)optional($item->addressRel)->addressPrefix ?: '-',
                    'dealUid'          => $item->dealUid,
                    'dealName'         => $dealUserInfo['username'] ?? $item['dealUid'],
                    'expiredAt'        => $item->expiredAt ? date('Y-m-d', $item->expiredAt) : '-',
                    'status'           => $item->status,
                    'statusText'       => SiteMissionEnum::STATUS_TEXT[$item->status] ?? '',
                    'originSource'     => self::SOURCE_3,
                    'originSourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_3] ?? '',
                ];
            }
        );

        return [
            'count'    => 0,
            'pageNum'  => $data['pageNum'],
            'pageSize' => $data['pageSize'],
            'list'     => $lists,
        ];
    }

    /**
     * 日常任务
     * @param array $data
     * @return array
     * @throws GuzzleException
     */
    public static function getDailyWhereList(array $data): array
    {
        if ($data['isOperate']) {
            $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
        }
        // 搜索匹配
        $searchRes = ['shopIds' => []];
        if ($data['search']['fyName']) {
            $searchRes = self::searchWhereRmsShop($data['search']['fyName'], true);
        } elseif ($data['search']['shopName']) {
            $searchRes = self::searchWhereRmsShop($data['search']['shopName']);
        }
        $sqlRaw = $sqlRawOne = $sqlRawTwo = '';
        if ($data['isApprovalRejected']) {
            $sqlRawOne = "  (businessType = " . TaskTemplateNodesModel::BUSINESS_TYPE_SUBMIT . " and isApprovalRejected = 1) ";
        }
        if ($data['dailyWhere']) {
            $sqlRawTwo = "  (businessType IN ( " . implode(',', $data['dailyWhere']) . " ) and isApprovalRejected = 0) ";
        }
        if ($sqlRawOne && $sqlRawTwo) {
            $sqlRaw .= " and ({$sqlRawOne} or  {$sqlRawTwo}) ";
        } else {
            if ($sqlRawOne) {
                $sqlRaw .= " and {$sqlRawOne} ";
            }
            if ($sqlRawTwo) {
                $sqlRaw .= " and  {$sqlRawTwo}  ";
            }
        }
        $paginator = DailyTaskLogsModel::query()
            ->join('kms_task', 'kms_task.businessId', '=', 'kms_daily_task_logs.id')
            ->whereRaw(
                "kms_task.id IN (
	SELECT
		id
	FROM
		kms_task
	WHERE
		id IN (
		SELECT
			taskId
		FROM
			kms_task_nodes
		WHERE
			id IN ( SELECT MAX( id ) FROM kms_task_nodes WHERE isDeleted = 0 GROUP BY taskId )
			AND isDeleted = 0 " . $sqlRaw . "
		)
		AND isDeleted = 0 and status > 0
	) "
            )
            ->when(
                in_array(
                    $data['role'], [
                        UserRoleService::ROLE_BASE_SUPERVISOR,
                    ]
                ), function ($query) use ($data) {
                $query->where('handlerUserId', $data['rmsUserId']);
            }
            )
            ->when(
                $data['search']['orderNo'], function ($query) use ($data) {
                $query->whereIn('id', $data['search']['orderNo']);
            }
            )
            ->when(
                $searchRes['shopIds'], function ($query) use ($searchRes) {
                $query->whereIn('shopId', $searchRes['shopIds']);
            }
            )
            ->when(
                self::checkRolePermissions($data['role'], 3) && $data['userIds'], function ($query) use ($data) {
                $query->where(
                    function ($query) use ($data) {
                        $query->whereIn('handlerUserId', $data['userIds'])
                            ->when(
                                in_array(
                                    $data['role'], [
                                        UserRoleService::ROLE_BASE_PROVINCE,
                                        UserRoleService::ROLE_BASE_CITY_MANAGER,
                                        UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                                    ]
                                ) && $data['isOperate'] && $data['userIds'], function ($query) use ($data) {
                                $query->orWhereRaw("JSON_CONTAINS(approveUserIds, JSON_ARRAY(" . implode(',', $data['userIds']) . "))");
                            }
                            );
                    }
                );
            }
            )
            ->orderByDesc('kms_daily_task_logs.id')
            ->select(['kms_daily_task_logs.*'])
            ->offset($data['pageNum'])
            ->limit($data['pageSize'])
            ->get();
//            ->paginate($data['pageSize'], ['kms_daily_task_logs.*'], 'pageNum', $data['pageNum']);


        //获取处理人
        $handlerUserIds = $paginator->pluck('handlerUserId')->toArray();
        $createdByUids  = $paginator->pluck('createdByUid')->toArray();
        $userInfo       = RmsUserService::getRmsUserInfoByUserIds(array_unique(array_merge($handlerUserIds, $createdByUids)))['data'] ?? [];
        $userList       = array_column($userInfo, 'username', 'id');

        $shopInfo = (new RmsShopApi())->getShopByIds($paginator->pluck('shopId')->toArray(), ['id', 'shopCode', 'name'])['data']['shopList'] ?? [];
        $shopList = array_column($shopInfo, null, 'id');

        $list = $paginator->map(
            function ($item) use ($shopList, $userList) {
                $data = [
                    'id'               => $item->id,
                    'shopId'           => $item->shopId,
                    'shopName'         => ($shopList[$item->shopId]['shopCode'] ?? '') . ' ' . ($shopList[$item->shopId]['name'] ?? '-'),
                    'handlerUserId'    => $item->handlerUserId,
                    'taskType'         => $item->taskType,
                    'taskTypeText'     => DailyTaskLogsModel::TASK_TYPE_TEXT[$item->taskType] ?? "",
                    'desc'             => $item->desc,
                    'descImg'          => $item->descImg,
                    'createdAt'        => $item->createdAt->toDateTimeString(),
                    'createdByUid'     => $item->createdByUid,
                    'handlerUserName'  => $userList[$item->handlerUserId] ?? '',
                    'createdUserName'  => $userList[$item->createdByUid] ?? '',
                    'originSource'     => self::SOURCE_5,
                    'originSourceText' => self::SOURCE_TEXT_MAPPING[self::SOURCE_5] ?? '',
                    'approveUserIds'   => $item->approveUserIds,
                ];
                if ($item->taskRel) {
                    $data['businessId'] = $item->taskRel->businessId ?? 0;
                    $data['templateId'] = $item->taskRel->templateId ?? 0;
                    $data['status']     = $item->taskRel->status ?? 0;
                    if (isset($item->taskRel->taskNodesRel) && count($item->taskRel->taskNodesRel)) {
                        $taskNodes                  = collect($item->taskRel->taskNodesRel)->sortByDesc('id')->first();
                        $data['step']               = $taskNodes->step;
                        $data['businessType']       = $taskNodes->businessType;
                        $data['businessTypeText']   = TaskTemplateNodesModel::BUSINESS_TYPE_TEXT[$taskNodes->businessType] ?? "";
                        $data['businessStatus']     = $taskNodes->businessStatus;
                        $data['businessStatusText'] = $taskNodes->businessStatusText;
                    }
                }
                return $data;
            }
        )->toArray();

        return [
            'list'      => $list,
            'count'     => 0,
            'pageCount' => ceil($data['pageNum'] / $data['pageSize']),
            'pageNum'   => $data['pageNum'],
            'pageSize'  => $data['pageSize'],
        ];
    }

    /**
     * 员工列表
     * @param int $rmsUserId
     * @param int $type
     * @param int $branchId
     * @param string $month
     * @param int $source
     * @return array
     * @throws ValidationException
     */
    public static function staffList(int $rmsUserId, int $type, int $branchId, string $month, int $source = 0): array
    {
        $getUserRole   = UserRoleService::getUserRole($rmsUserId);
        $role          = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        $provinceCodes = $getUserRole['userResponsibleArea']['area']['province'] ?? [];
        if (self::checkRolePermissions($role, 6)) {
            $provinceCodes = [];// 不判断省区
        }

        $monthTime    = strtotime($month);                                               // 本月开始时间
        $monthEndTime = strtotime(date('Y-m-01', strtotime('+1 month', $monthTime))) - 1;// 本月结束时间

        if ($branchId) {// 通过分公司查询
            $getProvinces = OpenShopOrganizationRegionMappingModel::query()
                ->where('manageId', $branchId)
                ->select(['provinceCode'])
                ->get()
                ->toArray();
            if (!$getProvinces) {
                return [];
            }
            $provinceCodes = array_column($getProvinces, 'provinceCode');
        }

        // 通过省区关联
        $manageIds = OpenShopOrganizationRegionMappingModel::query()
            ->when(
                $provinceCodes, function ($query) use ($provinceCodes) {
                $query->whereIn('provinceCode', $provinceCodes);
            }
            )
            ->pluck('manageId')
            ->unique()
            ->toArray();
        if (!$manageIds) {
            return [];
        }

        if ($source) {// 省总查询督导&选址
            $openShopType = [
                OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER,
                OpenShopOrganizationManageUserModel::TYPE_SITE_SELECTION_DEVELOPMENT,
            ];
        } else {
            if ($type == OpenShopUserTaskTargetModel::TYPE_1) {
                $openShopType = [OpenShopOrganizationManageUserModel::TYPE_SITE_SELECTION_DEVELOPMENT];
            } else {
                $openShopType = [OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER];
            }
        }

        // 查询设置的督导&选址
        $managers = OpenShopOrganizationManageUserModel::query()
            ->with(['fsUserRel'])
            ->whereIn('manageId', $manageIds)
            ->whereIn('type', $openShopType)
            ->select(['userId', 'name'])
            ->groupBy('userId')
            ->get()
            ->map(
                function ($item) {
                    return [
                        'userId' => $item->userId,
                        'name'   => $item->name,
                        'avatar' => $item->fsUserRel->avatar ?? '',
                    ];
                }
            )
            ->toArray();

        if ($source && in_array($role, [UserRoleService::ROLE_SPECIAL_1, UserRoleService::ROLE_SPECIAL_2])) {// 增加大客户开发人员
            if ($managers) {
                $managers = collect($managers)->keyBy('userId')->toArray();
            }
            KmsUser::query()
                ->where('rootDepartmentName', '选址开发中心')
                ->where('isExited', KmsUser::IS_EXITED_OFF)
                ->select(['rmsUserId', 'name', 'nickname', 'avatar'])
                ->get()
                ->map(
                    function ($item) use (&$managers) {
                        if (!isset($managers[$item->rmsUserId])) {
                            $managers[] = [
                                'userId' => $item->rmsUserId,
                                'name'   => $item->nickname . '(' . $item->name . ')',
                                'avatar' => $item->avatar,
                            ];
                        }
                    }
                );
            $managers = array_values($managers);
        }

        if ($source) {// 省总查询督导&选址 直接返回用户mappings
            return $managers;
        }
        $userIds = array_unique(array_column($managers, 'userId'));

        $siteLocationCompleted = $siteLocationPendingUpdated = $taskLogCompleted = $taskLogIng =
        $submitCruiseOrder = $completedCruiseOrder = $userTaskTarget = [];
        if ($type == OpenShopUserTaskTargetModel::TYPE_1) {// 选址

            // 完成落址
            $siteLocationCompleted = self::getSiteLocationByStaff($provinceCodes, $userIds, $monthTime, $monthEndTime)
                ->whereIn('siteStatus', [OpenShopSiteLocationModel::SITE_STATUS_4])
                ->keyBy('developConsultantId')
                ->toArray();

            // 选址审批
            $siteLocationPendingUpdated = self::getSiteLocationByStaff($provinceCodes, $userIds)
                ->whereIn('siteStatus', [OpenShopSiteLocationModel::SITE_STATUS_3])
                ->keyBy('developConsultantId')
                ->toArray();
        } else {// 督导

            // 开业报告
            //分母：预估开业日期在本月的门店数 分子：预估开业日期在本月，且提交了开业报告的门店数

            // 进行中
            $submitCruiseOrder = self::getCruiseOrderByStaff(
                $provinceCodes, $userIds, $monthTime, $monthEndTime,
                [CruiseOrderModel::STATUS_NOT_SUBMIT, CruiseOrderModel::STATUS_NOT_REVIEW, CruiseOrderModel::STATUS_WAIT_MODIFY_EXT, CruiseOrderModel::STATUS_COMPLETE]
            )->keyBy('managerUid')->toArray();


            // 已开业
            $completedCruiseOrder = self::getCruiseOrderByStaff($provinceCodes, $userIds, $monthTime, $monthEndTime, [CruiseOrderModel::STATUS_COMPLETE])
                ->keyBy('managerUid')
                ->toArray();

            // 新日常任务
            $taskLogIng       = self::getTaskNodesByStaff($userIds, TaskModel::TASK_STATUS_ING, $monthTime, $monthEndTime)['taskLogIng'];
            $taskLogCompleted = self::getTaskNodesByStaff($userIds, TaskModel::TASK_STATUS_FINISHED, $monthTime, $monthEndTime)['taskLogCompleted'];
        }

        // 查询对应的目标
        $userTaskTarget = OpenShopUserTaskTargetModel::query()
            ->whereIn('userId', $userIds)
            ->where('type', $type)
            ->where('targetTime', $monthTime)//目标记录时间
            ->select('userId', 'type', 'targetCount', 'finishCount')
            ->get()->keyBy('userId')->toArray();

        foreach ($managers as &$user) {
            $user['siteLocationTargetCount']     = $userTaskTarget[$user['userId']]['targetCount'] ?? 0;    //选址目标数
            $user['siteLocationFinishCount']     = $siteLocationCompleted[$user['userId']]['num'] ?? 0;     //选址完成数
            $user['siteLocationInApprovalCount'] = $siteLocationPendingUpdated[$user['userId']]['num'] ?? 0;//选址审批数

            $user['startBusinessTargetCount'] = $submitCruiseOrder[$user['userId']]['num'] ?? 0;   //开业目标数
            $user['startBusinessFinishCount'] = $completedCruiseOrder[$user['userId']]['num'] ?? 0;//开业完成数

            // (日常任务分母的计算规则:本月完成的任务+所有未完成的任务
            $user['targetCount'] = ($taskLogIng[$user['userId']]['num'] ?? 0) +
                ($taskLogCompleted[$user['userId']]['num'] ?? 0);                 //日常任务目标数
            $user['finishCount'] = $taskLogCompleted[$user['userId']]['num'] ?? 0;//日常任务完成数

            $user['targetId'] = $userTaskTarget[$user['userId']]['id'] ?? 0;         //设置目标记录id
            $user['username'] = $user['name'];
        }

        return [
            'managers' => $managers,
            'type'     => $type,
            'typeText' => OpenShopUserTaskTargetModel::TYPE_TEXT_MAPPING[$type] ?? "",
        ];
    }

    /**
     * 保存员工任务目标
     * @param Request $request
     * @param int $rmsUserId
     * @return array
     */
    public static function setStaffTarget(Request $request, int $rmsUserId): array
    {
        $data  = $request->data;
        $month = $request->month;
        $time  = time();

        $monthTime = strtotime($month);
        try {
            $batchData = [];
            foreach ($data as $v) {
                $userTaskTargetModel = OpenShopUserTaskTargetModel::query()
                    ->where('userId', $v['userId'])
                    ->where('targetTime', $monthTime)
                    ->where('type', OpenShopUserTaskTargetModel::TYPE_1)
                    ->first();
                if ($userTaskTargetModel) {
                    if ($userTaskTargetModel->targetCount != $v['targetCount']) {
                        $userTaskTargetModel->targetCount  = $v['targetCount'];
                        $userTaskTargetModel->updatedAt    = $time;
                        $userTaskTargetModel->updatedByUid = $rmsUserId;
                        $userTaskTargetModel->save();
                    }
                } else {
                    $batchData[] = [
                        'userId'       => $v['userId'],
                        'targetCount'  => $v['targetCount'],
                        'targetTime'   => $monthTime,
                        'type'         => OpenShopUserTaskTargetModel::TYPE_1,
                        'createdAt'    => $time,
                        'createdByUid' => $rmsUserId,
                    ];
                }
            }
            if ($batchData) {
                OpenShopUserTaskTargetModel::insertData($batchData);
            }
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "保存员工任务目标失败");
        }
        return [];
    }


    /**
     * 根据身份获取分公司列表
     * @param int $rmsUserId
     * @return array
     * @throws ValidationException
     */
    public static function branchList(int $rmsUserId): array
    {
        $getUserRole   = UserRoleService::getUserRole($rmsUserId);
        $role          = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        $provinceCodes = $getUserRole['userResponsibleArea']['area']['province'] ?? [];
        if (self::checkRolePermissions($role, 6)) {
            $provinceCodes = [];// 不判断省区
        }
        $manageIds  = [];

        // 城市经理 查询对应省区
        if ($role == UserRoleService::ROLE_BASE_CITY_MANAGER) {
            OpenShopOrganizationManageUserModel::query()
                ->where('userId', $rmsUserId)
                ->where('type', OpenShopOrganizationManageUserModel::TYPE_CITY_MANAGER)
                ->get()
                ->map(
                    function ($item) use (&$provinceCodes) {
                        $provinceCode = array_column($item->addressCodesArr ?? [], 'provinceCode');
                        if ($provinceCode) {
                            $provinceCodes = array_unique(array_merge($provinceCodes, $provinceCode));
                        }
                    }
                );
        }

        // 开发城市经理 查询对应省区
        if ($role == UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER) {
            OpenShopOrganizationManageUserModel::query()
                ->where('userId', $rmsUserId)
                ->where('type', OpenShopOrganizationManageUserModel::TYPE_DEVELOP_CITY_MANAGER)
                ->get()
                ->map(
                    function ($item) use (&$provinceCodes) {
                        $provinceCode = array_column($item->addressCodesArr ?? [], 'provinceCode');
                        if ($provinceCode) {
                            $provinceCodes = array_unique(array_merge($provinceCodes, $provinceCode));
                        }
                    }
                );
        }

        // 查询省份对应分公司
        $managers = [];
        OpenShopOrganizationRegionMappingModel::query()
            ->with(['organizationManageRel'])
            ->when(
                $manageIds, function ($query) use ($manageIds) {
                $query->whereIn('manageId', $manageIds);
            }
            )
            ->when(
                $provinceCodes, function ($query) use ($provinceCodes) {
                $query->whereIn('provinceCode', $provinceCodes);
            }
            )
            ->get()
            ->map(
                function ($item) use (&$managers) {
                    $id = $item->organizationManageRel->id ?? 0;
                    if ($id && !isset($managers[$id])) {
                        $managers[$id] = [
                            'id'   => $id,
                            'name' => $item->organizationManageRel->name ?? 0,
                        ];
                    }
                }
            );
        if ($managers) {
            sort($managers);
        }
        return [
            'list' => array_values($managers),
        ];
    }


    /**
     * 用户列表-省总查询督导&选址
     * @param int $rmsUserId
     * @return array
     * @throws ValidationException
     */
    public static function staffUserList(int $rmsUserId): array
    {
        $getUserRole = UserRoleService::getUserRole($rmsUserId);
        $role        = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        if (!self::checkRolePermissions($role, 3)) {
            return [];
        }
        return self::staffList($rmsUserId, 0, 0, '', 1);
    }

    /**
     * 判断用户角色权限
     * @param $role
     * @param $type
     * @return bool
     */
    public static function checkRolePermissions($role, $type): bool
    {
        switch ($type) {
            case 1://新建日常任务
                $roleData = [
                    UserRoleService::ROLE_BASE_PROVINCE,          //省总
                    UserRoleService::ROLE_BASE_CITY_MANAGER,      //城市经理
                    UserRoleService::ROLE_BASE_SUPERVISOR,        //督导
                    UserRoleService::ROLE_BASE_WAR_REGION,        //战区
                ];
                break;
            case 2://显示员工列表
                $roleData = [
                    UserRoleService::ROLE_BASE_PROVINCE,            //省总
                    UserRoleService::ROLE_BASE_CITY_MANAGER,        //城市经理
                    UserRoleService::ROLE_BASE_OBSERVER,            //观察者
                    UserRoleService::ROLE_SPECIAL_0,                //超级管理员
                    UserRoleService::ROLE_SPECIAL_1,                //大黄蜂
                    UserRoleService::ROLE_SPECIAL_2,                //赤瞳
                    UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,//开发城市经理
                    UserRoleService::ROLE_BASE_WAR_REGION,          //战区
                ];
                break;
            case 3://搜索人员
                $roleData = [
                    UserRoleService::ROLE_BASE_PROVINCE,            //省总
                    UserRoleService::ROLE_BASE_CITY_MANAGER,        //城市经理
                    UserRoleService::ROLE_BASE_OBSERVER,            //观察者
                    UserRoleService::ROLE_SPECIAL_0,                //超级管理员
                    UserRoleService::ROLE_SPECIAL_1,                //大黄蜂
                    UserRoleService::ROLE_SPECIAL_2,                //赤瞳
                    UserRoleService::ROLE_SPECIAL_3,                //灵文
                    UserRoleService::ROLE_SPECIAL_4,                //辰月
                    UserRoleService::ROLE_SPECIAL_5,                //胖虎
                    UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,//开发城市经理
                    UserRoleService::ROLE_BASE_WAR_REGION,          //战区
                ];
                break;
            case 4://新建房源线索
                $roleData = [
                    UserRoleService::ROLE_BASE_PROVINCE,                          //省总
                    UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT,        //选址开发
                    UserRoleService::ROLE_BASE_KAM,                               //大客户开发
                    UserRoleService::ROLE_BASE_WAR_REGION,                        //战区
                ];
                break;
            case 5://显示收藏任务
                $roleData = [
                    UserRoleService::ROLE_BASE_KAM,                               //大客户开发
                ];
                break;
            case 6://不判断省区
                $roleData = [
                    UserRoleService::ROLE_SPECIAL_0,                //超级管理员
                    UserRoleService::ROLE_BASE_OBSERVER,            //观察者
                    UserRoleService::ROLE_SPECIAL_1,                //大黄蜂
                    UserRoleService::ROLE_SPECIAL_2,                //赤瞳
                    UserRoleService::ROLE_SPECIAL_3,                //灵文
                    UserRoleService::ROLE_SPECIAL_4,                //辰月
                ];
                break;
            default:
                $roleData = [];
        }
        if ($roleData && in_array($role, $roleData)) {
            return true;
        }
        return false;
    }

    /**
     * 通过省市区code获取对应的单号
     * @param $data
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Support\Traits\Conditionable|mixed|string
     */
    public static function getOrderNosByProvinceCode($data)
    {
        if ($data['provinceCodes'] || $data['cityCodes'] || $data['areaCodes']) {
            return OpenShopAddressModel::query()
                ->when(
                    $data['provinceCodes'], function ($query) use ($data) {
                    $query->whereIn('provinceCode', $data['provinceCodes']);
                }
                )
                ->when(
                    $data['cityCodes'], function ($query) use ($data) {
                    $query->orWhereIn('cityCode', $data['cityCodes']);
                }
                )
                ->when(
                    $data['areaCodes'], function ($query) use ($data) {
                    $query->orWhereIn('areaCode', $data['areaCodes']);
                }
                )
                ->select('orderNo');
        }
        return '';
    }


    /**
     * 开发待指派 单独查询
     * @param array $data
     * @return array
     */
    public static function getOrderNosBySiteMiss(array $data): array
    {
        $child = self::getOrderNosByProvinceCode($data);
        if ($data['isOperate'] || $data['role'] == UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT || (in_array(
                    $data['role'], [
                        UserRoleService::ROLE_SPECIAL_2,
                        UserRoleService::ROLE_SPECIAL_5,
                        UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                    ]
                ) && $data['isOperate'] && in_array(MissionTemplateEnum::STEP_STATUS_3, $data['siteMissWhere']))) {
            $data['userIds'] = array_merge($data['userIds'], [$data['rmsUserId']]);
        }
        return OpenShopSiteMissionModel::query()
            ->where('status', SiteMissionEnum::STATUS_1)
            ->when(
                $data['orderNos'], function ($query) use ($data) {
                $query->whereIn('orderNo', $data['orderNos']);
            }
            )
            ->when(
                $data['userIds'], function ($query) use ($data) {
                $query->whereIn('dealUid', $data['userIds']);
            }
            )
            ->when(
                $child, function ($query) use ($child) {
                $query->whereRaw('orderNo in (' . BaseModel::toSqlWithParam($child) . ')');
            }
            )
            ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_3)
            ->where('isShow', 1)
            ->where('orderStatus', 1)
            ->pluck('orderNo')->toArray();
    }

    /**
     * 员工管理-选址数据查询
     * @param array $provinceCodes
     * @param array $userIds
     * @param int $startTime
     * @param int $endTime
     */
    public static function getSiteLocationByStaff(array $provinceCodes, array $userIds, int $startTime = 0, int $endTime = 0)
    {
        return OpenShopSiteLocationModel::query()
            ->when(
                $provinceCodes, function ($query) use ($provinceCodes) {
                $query->whereIn('provinceCode', $provinceCodes);
            }
            )
            ->when(
                $userIds, function ($query) use ($userIds) {
                $query->whereIn("developConsultantId", $userIds);
            }
            )
            ->when(
                $startTime && $endTime, function ($query) use ($startTime, $endTime) {
                $query->whereBetween("ctSubmitTime", [$startTime, $endTime]);  // 商家已确认选址时间
            }
            )
            ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_OPEN_SHOP])
            ->selectRaw("developConsultantId,siteStatus,count(1) num")
            ->groupBy(['developConsultantId', 'siteStatus'])->get();
    }

    /**
     * 员工管理-督导-开业数据查询
     * @param array $provinceCodes
     * @param array $userIds
     * @param int $startTime
     * @param int $endTime
     * @param array $status
     */
    public static function getCruiseOrderByStaff(array $provinceCodes, array $userIds, int $startTime, int $endTime, array $status)
    {
        return CruiseOrderModel::query()
            ->leftJoin('open_shop_location', 'open_shop_location.orderNo', '=', 'cruise_order.orderNo')
            ->leftJoin('open_shop_main_process', 'open_shop_main_process.orderNo', '=', 'cruise_order.orderNo')
            ->leftJoin('open_shop_order_manager', 'open_shop_order_manager.mainProcessId', '=', 'open_shop_main_process.id')
            ->where('cruise_order.type', CruiseOrderModel::TYPE_NEW_SHOP_HELP)
            ->where('cruise_order.isDeleted', 0)
            ->where('open_shop_order_manager.isDeleted', 0)
            ->whereIn('cruise_order.status', $status)
            ->whereBetween('open_shop_location.openTime', [$startTime, $endTime])//预计开业时间
            ->when(
                $provinceCodes, function ($query) use ($provinceCodes) {
                $child = OpenShopAddressModel::query()
                    ->whereIn('provinceCode', $provinceCodes)
                    ->select('orderNo');
                $query->whereRaw("cruise_order.orderNo in (" . BaseModel::toSqlWithParam($child) . ')');
            }
            )
            ->when(
                $userIds, function ($query) use ($userIds) {
                $query->whereIn('open_shop_order_manager.managerUid', $userIds)
                    ->where('open_shop_order_manager.type', OpenShopOrderManagerModel::MANAGER_TYPE_5);
            }
            )
            ->selectRaw("open_shop_order_manager.managerUid,count(1) num")
            ->groupBy(['open_shop_order_manager.managerUid'])->get();
    }

    /**
     * 员工管理-督导-日常数据查询
     * @param array $userIds
     * @param int $status
     * @param int $startTime
     * @param int $endTime
     * @return array[]
     */
    public static function getTaskNodesByStaff(array $userIds, int $status, int $startTime = 0, int $endTime = 0): array
    {
        $taskLogIng = $taskLogCompleted = [];
        TaskNodesModel::query()
            ->join('kms_task', 'kms_task.id', '=', 'kms_task_nodes.taskId')
            ->join('kms_daily_task_logs', 'kms_task.businessId', '=', 'kms_daily_task_logs.id')
            ->whereRaw("kms_task_nodes.id IN ( SELECT MAX( id ) FROM kms_task_nodes GROUP BY taskId ) ")
            ->when(
                $userIds, function ($query) use ($userIds) {
                $query->whereIn('kms_daily_task_logs.handlerUserId', $userIds);
            }
            )
            ->where('kms_task_nodes.isDeleted', 0)
            ->where('kms_task.isDeleted', 0)
            ->where('kms_daily_task_logs.isDeleted', 0)
            ->when(
                $startTime && $endTime, function ($query) use ($status, $startTime, $endTime) {
                if ($status == TaskModel::TASK_STATUS_ING) {
                    $query->whereBetween("kms_task.createdAt", [$startTime, $endTime]);  // 任务创建时间
                } else {
                    $query->whereBetween("kms_task.updatedAt", [$startTime, $endTime]);  // 任务完成时间
                }
            }
            )
            ->where('kms_task.status', $status)
            ->groupBy(["kms_daily_task_logs.handlerUserId", "kms_task.status"])
            ->selectRaw("kms_daily_task_logs.handlerUserId,kms_task.status,count(1) num")
            ->get()
            ->map(
                function ($item) use (&$taskLogIng, &$taskLogCompleted) {
                    $handlerUserId = $item->handlerUserId ?? 0;
                    $status        = $item->status ?? 0;
                    $num           = $item->num ?? 0;
                    if ($status == TaskModel::TASK_STATUS_ING) {
                        if (isset($taskLogIng[$handlerUserId])) {
                            $taskLogIng[$handlerUserId]['num'] += $num;
                        } else {
                            $taskLogIng[$handlerUserId]['num'] = $num;
                        }
                    }
                    if ($status == TaskModel::TASK_STATUS_FINISHED) {
                        if (isset($taskLogCompleted[$handlerUserId])) {
                            $taskLogCompleted[$handlerUserId]['num'] += $num;
                        } else {
                            $taskLogCompleted[$handlerUserId]['num'] = $num;
                        }
                    }
                }
            );
        return [
            'taskLogIng'       => $taskLogIng,
            'taskLogCompleted' => $taskLogCompleted,
        ];
    }

    /**
     * 模糊搜索rms门店
     * @param string $name
     * @param bool $isAddress
     * @return array
     * @throws \Exception
     */
    public static function searchWhereRmsShop(string $name, bool $isAddress = false): array
    {
        $shopIds = [];
        if ($name) {
            $shopList = ShopService::getShopListByLikeSearch($name, ['id', 'shopCode'], $isAddress);
            if (!$shopList) {
                return ['shopIds' => ['0']];
            }
            $shopIds = array_column($shopList, 'id');
        }
        return ['shopIds' => $shopIds];
    }

    /**
     * 模糊匹配查询
     * @param array $search
     * @return array
     */
    public static function searchWhereByName(array $search): array
    {
        $orderNos = $rmsUserIds = [];
        if (mb_strlen($search['shopName'])) {

            // 加盟商姓名
            OpenShopUserIdentityCardModel::query()
                ->with(['mainProcessRel'])
                ->where('name', 'like', "%{$search['shopName']}%")
                ->get()
                ->each(
                    function ($item) use (&$orderNos) {
                        if ($item->mainProcessRel != null) {
                            foreach ($item->mainProcessRel as $value) {
                                $orderNos[] = $value->orderNo;
                            }
                        }
                    }
                );
            if (!$orderNos) {
                $orderNos = ['0'];
            }

            // 门店id/编号
            $shopCodes = [];
            if (!is_numeric($search['shopName'])) {
                $shopList  = ShopService::getShopListByLikeSearch($search['shopName'], ['id', 'shopCode']);
                $shopCodes = array_column($shopList, 'shopCode');
            }
            if ($shopCodes || is_numeric($search['shopName'])) {
                $getOrderNos = OpenShopSignOrderModel::query()
                    ->when(
                        is_numeric($search['shopName']), function ($query) use ($search) {
                        $query->where('shopCode', 'like', "%{$search['shopName']}%");
                    }
                    )
                    ->when(
                        $shopCodes, function ($query) use ($shopCodes) {
                        $query->orWhereIn('shopCode', $shopCodes);
                    }
                    )
                    ->pluck('orderNo')
                    ->toArray();
                if (!$getOrderNos) {
                    $getOrderNos = ['0'];
                }
            } else {
                $getOrderNos = ['0'];
            }

            if ($getOrderNos) {
                $orderNos = array_unique(array_merge($orderNos, $getOrderNos));
            }

        }

        if (mb_strlen($search['handlerName']) && !is_numeric($search['handlerName'])) {

            // 处理人
            $rmsUserIds = self::getRmsUserIdByUserName($search['handlerName']);
        }

        return ['orderNos' => $orderNos, 'rmsUserIds' => $rmsUserIds];
    }

    /**
     * 非房源类型根据开店订单地址搜索
     * @param $search
     * @return array
     */
    public static function searchWhereByFyName($search): array
    {
        $getOrderNos = [];
        if (isset($search['fyName']) && mb_strlen($search['fyName']) && !is_numeric($search['fyName'])) {

            // 门店地址
            $getOrderNos = OpenShopAddressModel::query()
                ->where("addressPrefix", "like", "%{$search['fyName']}%")
                ->orWhere("addressDetail", "like", "%{$search['fyName']}%")
                ->pluck('orderNo')
                ->toArray();
            if (!$getOrderNos) {
                $getOrderNos = ['0'];
            }
        }
        return $getOrderNos;
    }


    /**
     * 门店tab总览
     * @param int $rmsUserId
     * @param array $search
     * @return array
     * @throws ValidationException
     */
    public static function shopTotal(int $rmsUserId, array $search): array
    {
        $getUserRole  = UserRoleService::getUserRole($rmsUserId);
        $role         = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        $roleDesc     = $getUserRole['desc'] ?? '';
        $allArea      = $getUserRole['userResponsibleArea']['all'] ?? false;
        $branchOffice = $getUserRole['homeBranchOffice']['branchOffice'] ?? [];
        $warZoneIds   = collect($getUserRole['warZone'])->pluck('id')->toArray();

        if ($warZoneIds) {// 返回战区对应的分公司
            $branchOffice = self::getBranchByWarZoneIds($warZoneIds);
        }

        $shopCodes = [];
        $username  = '';
        if (mb_strlen($search['shopName'])) {
            if (is_numeric($search['shopName'])) {
                $shopCodes = [$search['shopName']];
            } else {
                $username  = $search['shopName'];
                $shopList  = ShopService::getShopListByLikeSearch($search['shopName'], ['id', 'shopCode']);
                $shopCodes = array_column($shopList, 'shopCode');
            }
        }

        $toBeDevelopment = $toBeLocated = $inProcess = $businessToPay = $businessToSign = 0;
        if (!in_array($role, [UserRoleService::ROLE_BASE_PREPARE, UserRoleService::ROLE_BASE_SUPERVISOR])) {//筹备

            $getShopCodesByCkDb = self::getShopCodesByCkDb($allArea, $branchOffice, $search, ['选址中']);
            $baseSql            = self::baseQuery(
                $username, $shopCodes, $search, $rmsUserId, $role
                , [MissionTemplateEnum::STEP_STATUS_3, MissionTemplateEnum::STEP_STATUS_4, MissionTemplateEnum::STEP_STATUS_5], $getShopCodesByCkDb
            );

            $site = $baseSql
                ->groupBy('open_shop_main_process.nowStepStatus')
                ->selectRaw('open_shop_main_process.nowStepStatus,count(1) num')
                ->get();

            $toBeDevelopment = $site
                ->where('nowStepStatus', MissionTemplateEnum::STEP_STATUS_3)//开发待指派
                ->sum('num');// 选址-开发待指派

            $toBeLocated = $site
                ->where('nowStepStatus', MissionTemplateEnum::STEP_STATUS_4)
                ->sum('num');// 选址-待提交

            $inProcess = $site
                ->where('nowStepStatus', MissionTemplateEnum::STEP_STATUS_5)
                ->sum('num');// 选址-流程中 待修改+待审核

            $businessToPay = 0;// 签约-商家待支付 观远没有此状态
            //            = self::baseQuery($username, $shopCodes, $search, $rmsUserId, $role, [MissionTemplateEnum::STEP_STATUS_1], [])
            //                ->count();

            $getShopCodesByCkDb = self::getShopCodesByCkDb($allArea, $branchOffice, $search, ['待签署']);
            $businessToBeSql    = self::baseQuery($username, $shopCodes, $search, $rmsUserId, $role, [MissionTemplateEnum::STEP_STATUS_2], $getShopCodesByCkDb);

            $businessToSign = $businessToBeSql
                ->count();// 签约-商家待签署
        }

        $getShopCodesByCkDb = self::getShopCodesByCkDb($allArea, $branchOffice, $search, ['筹备中']);
        $preBaseSql         = self::baseQuery(
            $username, $shopCodes, $search, $rmsUserId, $role, [
            MissionTemplateEnum::STEP_STATUS_6, MissionTemplateEnum::STEP_STATUS_9,
            MissionTemplateEnum::STEP_STATUS_7, MissionTemplateEnum::STEP_STATUS_8,
            MissionTemplateEnum::STEP_STATUS_11, MissionTemplateEnum::STEP_STATUS_13,
            MissionTemplateEnum::STEP_STATUS_14, MissionTemplateEnum::STEP_STATUS_15,
            MissionTemplateEnum::STEP_STATUS_16, MissionTemplateEnum::STEP_STATUS_17, MissionTemplateEnum::STEP_STATUS_10
        ], $getShopCodesByCkDb
        )
            ->groupBy('open_shop_main_process.nowStepStatus')
            ->selectRaw('open_shop_main_process.nowStepStatus,count(1) num')->get();

        $toBeConfirmed = $preBaseSql
            ->whereIn('nowStepStatus', [MissionTemplateEnum::STEP_STATUS_6])
            ->sum('num');// 筹备-待确认建店

        $toBeBuild = $preBaseSql
            ->whereIn(
                'nowStepStatus', [
                    MissionTemplateEnum::STEP_STATUS_9,
                    MissionTemplateEnum::STEP_STATUS_7, MissionTemplateEnum::STEP_STATUS_8,
                    MissionTemplateEnum::STEP_STATUS_11, MissionTemplateEnum::STEP_STATUS_13,
                    MissionTemplateEnum::STEP_STATUS_14, MissionTemplateEnum::STEP_STATUS_15,
                    MissionTemplateEnum::STEP_STATUS_16, MissionTemplateEnum::STEP_STATUS_17
                ]
            )
            ->sum('num');// 筹备-待施工入场

        $toBeFinish = $preBaseSql
            ->whereIn('nowStepStatus', [MissionTemplateEnum::STEP_STATUS_10])
            ->sum('num');// 筹备-待施工完成

        // 待开业
        $getShopCodesByCkDb = self::getShopCodesByCkDb($allArea, $branchOffice, $search, ['筹备中']);
        $baseSql            = self::baseQuery($username, $shopCodes, $search, $rmsUserId, $role, [MissionTemplateEnum::STEP_STATUS_18], $getShopCodesByCkDb);
        $toBeOpened         = $baseSql->count();// 筹备-待开业

        $yesterday = date('Y-m-d', strtotime('-1 day'));

        $businessShopCodes = GuanyuanSyncShopBusinessModel::query()
            ->where('date', $yesterday)
            ->pluck('code')
            ->toArray();// 昨天有数据的门店

        // 已开业
        $getShopCodesByCkDb = self::getShopCodesByCkDb($allArea, $branchOffice, $search, ['正常营业'], $businessShopCodes);

        $baseSql = self::baseQuery($username, $shopCodes, $search, $rmsUserId, $role, [MissionTemplateEnum::STEP_STATUS_18, MissionTemplateEnum::STEP_STATUS_999], $getShopCodesByCkDb);

        $sql     = clone $baseSql;
        $openIng = $sql
            ->count();// 已开业-在营

        $sql             = clone $baseSql;
        $yesterdayActive = $sql
            ->whereIn('open_shop_sign_order.shopCode', $businessShopCodes)
            ->count();// 已开业-昨日活跃

        $sql              = clone $baseSql;
        $yesterdayDormant = $sql
            ->whereNotIn('open_shop_sign_order.shopCode', $businessShopCodes)
            ->count();// 已开业-昨日休眠

        $getShopCodesByCkDb = self::getShopCodesByCkDb($allArea, $branchOffice, $search, ['暂停营业']);
        $baseSql            = self::baseQuery($username, $shopCodes, $search, $rmsUserId, $role, [MissionTemplateEnum::STEP_STATUS_18, MissionTemplateEnum::STEP_STATUS_999], $getShopCodesByCkDb);

        $halt = $baseSql->count();// 已开业-暂停营业

        // 全阶段总数 数据去重
        $getShopCodesByCkDb = self::getShopCodesByCkDb($allArea, $branchOffice, $search, ['选址中', '筹备中', '正常营业', '暂停营业', '待签署']);
        $baseSql            = self::baseQuery(
            $username, $shopCodes, $search, $rmsUserId, $role, [
            MissionTemplateEnum::STEP_STATUS_3, MissionTemplateEnum::STEP_STATUS_4,
            MissionTemplateEnum::STEP_STATUS_5, MissionTemplateEnum::STEP_STATUS_6,
            MissionTemplateEnum::STEP_STATUS_9, MissionTemplateEnum::STEP_STATUS_10,
            MissionTemplateEnum::STEP_STATUS_7, MissionTemplateEnum::STEP_STATUS_8,
            MissionTemplateEnum::STEP_STATUS_11, MissionTemplateEnum::STEP_STATUS_13,
            MissionTemplateEnum::STEP_STATUS_14, MissionTemplateEnum::STEP_STATUS_15,
            MissionTemplateEnum::STEP_STATUS_16, MissionTemplateEnum::STEP_STATUS_17,
            MissionTemplateEnum::STEP_STATUS_18, MissionTemplateEnum::STEP_STATUS_999,
        ], $getShopCodesByCkDb);
        $count              = $baseSql->count();

        $total = [
            [
                'total'    => $businessToPay + $businessToSign,
                'typeText' => '签约',
                'type'     => implode(',', [self::TYPE_13]),
                'child'    => [
                    [
                        'total'    => $businessToSign,
                        'type'     => self::TYPE_13,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_13],
                    ],
                ],
            ],
            [
                'total'    => $toBeDevelopment + $toBeLocated + $inProcess,
                'typeText' => '选址',
                'type'     => implode(',', [self::TYPE_1, self::TYPE_2, self::TYPE_3]),
                'child'    => [
                    [
                        'total'    => $toBeDevelopment,
                        'type'     => self::TYPE_1,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_1],
                    ], [
                        'total'    => $toBeLocated,
                        'type'     => self::TYPE_2,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_2],
                    ], [
                        'total'    => $inProcess,
                        'type'     => self::TYPE_3,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_3],
                    ],
                ],
            ],
            [
                'total'    => $toBeConfirmed + $toBeBuild + $toBeFinish + $toBeOpened,
                'typeText' => '筹备',
                'type'     => implode(',', [self::TYPE_4, self::TYPE_5, self::TYPE_6, self::TYPE_7]),
                'child'    => [
                    [
                        'total'    => $toBeConfirmed,
                        'type'     => self::TYPE_4,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_4],
                    ], [
                        'total'    => $toBeBuild,
                        'type'     => self::TYPE_5,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_5],
                    ], [
                        'total'    => $toBeFinish,
                        'type'     => self::TYPE_6,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_6],
                    ], [
                        'total'    => $toBeOpened,
                        'type'     => self::TYPE_7,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_7],
                    ],
                ],
            ],
            [
                'total'    => $openIng + $halt,
                'typeText' => '已开业',
                'type'     => implode(',', [self::TYPE_8, self::TYPE_9, self::TYPE_10, self::TYPE_11]),
                'child'    => [
                    [
                        'total'    => $openIng,
                        'type'     => self::TYPE_8,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_8],
                    ], [
                        'total'    => $halt,
                        'type'     => self::TYPE_9,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_9],
                    ], [
                        'total'    => $yesterdayActive,
                        'type'     => self::TYPE_10,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_10],
                    ], [
                        'total'    => $yesterdayDormant,
                        'type'     => self::TYPE_11,
                        'typeText' => self::SHOP_TYPE_TEXT_MAPPING[self::TYPE_11],
                    ],
                ],
            ],
        ];

        return [
            'total' => $total,
            'count' => $count,
            'role'  => [
                'role'         => $role,
                'roleDesc'     => $roleDesc,
                "billboardBtn" => in_array(
                    $role, [
                        UserRoleService::ROLE_SPECIAL_0,
                        UserRoleService::ROLE_SPECIAL_1,
                        UserRoleService::ROLE_SPECIAL_2,
                        UserRoleService::ROLE_BASE_PROVINCE,
                        UserRoleService::ROLE_BASE_CITY_MANAGER,
                        UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                        UserRoleService::ROLE_BASE_OBSERVER
                    ]
                ),//【风云榜入口权限】(同首页)
            ]
        ];

    }

    /**
     * 门店tab-列表
     * @param int $rmsUserId
     * @param array $search
     * @param int $pageSize
     * @param int $pageNum
     * @return array
     * @throws ValidationException
     */
    public static function shopTabList(int $rmsUserId, array $search, int $pageSize, int $pageNum): array
    {
        $getUserRole  = UserRoleService::getUserRole($rmsUserId);
        $role         = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        $allArea      = $getUserRole['userResponsibleArea']['all'] ?? false;
        $branchOffice = $getUserRole['homeBranchOffice']['branchOffice'] ?? [];
        $warZoneIds   = collect($getUserRole['warZone'])->pluck('id')->toArray();

        if ($warZoneIds) {// 返回战区对应的分公司
            $branchOffice = self::getBranchByWarZoneIds($warZoneIds);
        }

        $shopCodes = [];
        $username  = '';
        if (mb_strlen($search['shopName'])) {
            if (is_numeric($search['shopName'])) {
                $shopCodes = [$search['shopName']];
            } else {
                $username  = $search['shopName'];
                $shopList  = ShopService::getShopListByLikeSearch($search['shopName'], ['id', 'shopCode']);
                $shopCodes = array_column($shopList, 'shopCode');
            }
        }

        $isYesDay       = $isAll = false;
        $businessStatus = $ckStatus = [];
        if (!$search['types']) {//默认查询
            $search['types'] = [
                self::TYPE_1, self::TYPE_2, self::TYPE_3, self::TYPE_4, self::TYPE_5, self::TYPE_6, self::TYPE_7,
                self::TYPE_8, self::TYPE_13
            ];
            $ckStatus        = ['选址中', '筹备中', '正常营业', '暂停营业', '待签署'];
            $isAll           = true;
        }
        if ($search['types']) {
            foreach ($search['types'] as $v) {
                if (in_array($role, [UserRoleService::ROLE_BASE_PREPARE, UserRoleService::ROLE_BASE_SUPERVISOR]) && in_array($v, [self::TYPE_1, self::TYPE_2, self::TYPE_3, self::TYPE_12, self::TYPE_13])) {//筹备
                    continue;
                }
                switch ($v) {
                    case self::TYPE_1:// 选址-开发待指派
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_3]);
                        $ckStatus       = array_unique(array_merge($ckStatus, ['选址中']));
                        break;
                    case self::TYPE_2:// 选址-待提交
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_4]);
                        $ckStatus       = array_unique(array_merge($ckStatus, ['选址中']));
                        break;
                    case self::TYPE_3:// 选址-流程中 待修改+待审核
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_5]);
                        $ckStatus       = array_unique(array_merge($ckStatus, ['选址中']));
                        break;
                    case self::TYPE_4:// 筹备-待确认建店
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_6]);
                        $ckStatus       = array_unique(array_merge($ckStatus, ['筹备中']));
                        break;
                    case self::TYPE_5:// 筹备-待施工入场
                        $businessStatus = array_merge(
                            $businessStatus, [
                                MissionTemplateEnum::STEP_STATUS_9,
                                MissionTemplateEnum::STEP_STATUS_7, MissionTemplateEnum::STEP_STATUS_8,
                                MissionTemplateEnum::STEP_STATUS_11, MissionTemplateEnum::STEP_STATUS_13,
                                MissionTemplateEnum::STEP_STATUS_14, MissionTemplateEnum::STEP_STATUS_15,
                                MissionTemplateEnum::STEP_STATUS_16, MissionTemplateEnum::STEP_STATUS_17
                            ]
                        );
                        $ckStatus       = array_unique(array_merge($ckStatus, ['筹备中']));
                        break;
                    case self::TYPE_6:// 筹备-待施工完成
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_10]);
                        $ckStatus       = array_unique(array_merge($ckStatus, ['筹备中']));
                        break;
                    case self::TYPE_7:// 筹备-待开业
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_18]);
                        $ckStatus       = array_unique(array_merge($ckStatus, ['筹备中']));
                        break;
                    case self::TYPE_8:// 已开业-在营
                        $ckStatus       = array_unique(array_merge($ckStatus, ['正常营业']));
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_18, MissionTemplateEnum::STEP_STATUS_999]);
                        break;
                    case self::TYPE_9:// 已开业-暂停营业
                        $ckStatus       = array_unique(array_merge($ckStatus, ['暂停营业']));
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_18, MissionTemplateEnum::STEP_STATUS_999]);
                        break;
                    case self::TYPE_10:// 已开业-昨日活跃
                    case self::TYPE_11:// 已开业-昨日休眠
                        $isYesDay       = true;
                        $ckStatus       = array_unique(array_merge($ckStatus, ['正常营业']));
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_18, MissionTemplateEnum::STEP_STATUS_999]);
                        break;
                    case self::TYPE_13:// 签约-商家待签署
                        $businessStatus = array_merge($businessStatus, [MissionTemplateEnum::STEP_STATUS_2]);
                        $ckStatus       = array_unique(array_merge($ckStatus, ['待签署']));
                        break;
                }
            }
        }

        $yesterday         = date('Y-m-d', strtotime('-1 day'));
        $businessShopCodes = GuanyuanSyncShopBusinessModel::query()
            ->where('date', $yesterday)
            ->pluck('code')->toArray();// 昨天有数据的门店

        $searchBusinessShopCodes = [];
        if (!$isAll && (in_array(self::TYPE_8, $search['types']) || $isYesDay) && $businessShopCodes) {
            $searchBusinessShopCodes = $businessShopCodes;
        }
        $getShopCodesByCkDb = self::getShopCodesByCkDb($allArea, $branchOffice, $search, $ckStatus, $searchBusinessShopCodes);

        $status = [SignOrderEnum::ORDER_STATUS_OK];
        if (in_array(MissionTemplateEnum::STEP_STATUS_999, $businessStatus)) {// 订单完成
            $status = [SignOrderEnum::ORDER_STATUS_OK, SignOrderEnum::ORDER_STATUS_COMPLETE];
        }
        $paginates = OpenShopSignOrderModel::query()
            ->leftJoin('open_shop_main_process', 'open_shop_main_process.id', '=', 'open_shop_sign_order.mainProcessId')
            ->leftJoin('guanyuan_sync_shop_list', 'guanyuan_sync_shop_list.code', '=', 'open_shop_sign_order.shopCode')
            ->whereIn('open_shop_sign_order.status', $status)
            ->when(
                in_array(MissionTemplateEnum::STEP_STATUS_999, $businessStatus) && !$isAll, function ($query) {
                $query->whereRaw(
                    'open_shop_sign_order.id IN ( SELECT max(a.id) FROM open_shop_sign_order a
                left join open_shop_main_process b on a.mainProcessId=b.id
                where a.status in (1,2) and b.nowStepStatus in (18,999)
                GROUP BY a.shopCode ) '
                );
            }
            )
            ->when(
                $search['orderNo'], function ($query) use ($search) {
                $query->where('open_shop_sign_order.orderNo', $search['orderNo']);
            }
            )
            ->when(
                $getShopCodesByCkDb, function ($query) use ($getShopCodesByCkDb) {
                $query->whereIn('open_shop_sign_order.shopCode', $getShopCodesByCkDb['shopCodes']);
            }
            )
            ->when(
                $businessStatus, function ($query) use ($businessStatus) {
                $query->whereIn('open_shop_main_process.nowStepStatus', $businessStatus);
            }
            )
            ->when(
                $businessShopCodes && $isYesDay, function ($query) use ($search, $businessShopCodes) {
                $query->when(
                    (in_array(self::TYPE_10, $search['types']) || in_array(self::TYPE_11, $search['types'])) && $businessShopCodes, function ($query) use ($businessShopCodes, $search) {
                    $query->where(
                        function ($query) use ($businessShopCodes, $search) {
                            $query->when(
                                in_array(self::TYPE_10, $search['types']) && !in_array(self::TYPE_11, $search['types']), function ($query) use ($businessShopCodes) {
                                $query->whereIn('open_shop_sign_order.shopCode', $businessShopCodes);//关联昨日数据记录
                            }
                            )->when(
                                in_array(self::TYPE_11, $search['types']) && !in_array(self::TYPE_10, $search['types']), function ($query) use ($businessShopCodes) {
                                $query->whereNotIn('open_shop_sign_order.shopCode', $businessShopCodes);
                            }
                            );
                        }
                    );
                }
                );
            }
            )
            ->when(
                $role == UserRoleService::ROLE_BASE_PREPARE, function ($query) use ($rmsUserId) {//筹备
                $query->leftJoin('open_shop_site_mission', 'open_shop_site_mission.orderNo', '=', 'open_shop_sign_order.orderNo')
                    ->where('open_shop_site_mission.dealUid', $rmsUserId)
                    ->where('open_shop_site_mission.isShow', 1)
                    ->where('open_shop_site_mission.orderStatus', 1)
                    ->where('open_shop_site_mission.isDeleted', 0);
            }
            )
            ->when(
                $role == UserRoleService::ROLE_BASE_SUPERVISOR, function ($query) use ($rmsUserId) {//督导
                $query->leftJoin('open_shop_order_manager', 'open_shop_order_manager.mainProcessId', '=', 'open_shop_main_process.id')
                    ->where('open_shop_order_manager.isDeleted', 0)
                    ->where('open_shop_order_manager.managerUid', $rmsUserId)
                    ->where('open_shop_order_manager.type', OpenShopOrderManagerModel::MANAGER_TYPE_5);//督导
            }
            )
            ->when(
                $search['shopGrade'] || $search['shopType'],
                function ($query) use ($search) {
                    $query->when(
                        $search['shopGrade'],
                        function ($query) use ($search) {
                            $query->whereIn("guanyuan_sync_shop_list.shopGrade", $search['shopGrade']);//门店最近营业额评级搜索
                        }
                    )->when(
                        $search['shopType'],
                        function ($query) use ($search) {
                            $query->whereIn("guanyuan_sync_shop_list.storeType", $search['shopType']);//门店最近营业额评级搜索
                        }
                    );
                }
            )
            ->when(
                $shopCodes || $username, function ($query) use ($username, $shopCodes) {
                $query->where(
                    function ($query) use ($username, $shopCodes) {
                        $query->when(
                            $shopCodes, function ($query) use ($shopCodes) {
                            $query->whereIn('open_shop_sign_order.shopCode', $shopCodes);
                        }
                        )->when(
                            $username, function ($query) use ($username) {
                            $query->orWhere('guanyuan_sync_shop_list.franchiseeRealName', 'like', "%{$username}%");
                        }
                        );
                    }
                );
            }
            )
            ->when(
                $search['cruiseOrderStatus'],
                function ($query) use ($search) {
                    $query->leftJoin('cruise_order', 'cruise_order.orderNo', '=', 'open_shop_sign_order.orderNo')
                        ->where('cruise_order.type', CruiseOrderModel::TYPE_NEW_SHOP_HELP)
                        ->whereIn("cruise_order.status", $search['cruiseOrderStatus']);
                }
            )
            ->with(
                [
                    'shopLocationRel' => function ($query) {
                        $query->select('orderNo', 'openTime');
                    },
                    'contractRel',
                ]
            )
            ->select(
                [
                    'open_shop_sign_order.*', 'open_shop_main_process.nowStepStatus', 'open_shop_main_process.shopId',
                    'guanyuan_sync_shop_list.province', 'guanyuan_sync_shop_list.city', 'guanyuan_sync_shop_list.district',
                    'guanyuan_sync_shop_list.franchiseeRealName', 'guanyuan_sync_shop_list.openBusinessDate',
                    'guanyuan_sync_shop_list.keyCity'
                ]
            )
            ->orderByDesc('open_shop_sign_order.id')
            ->offset($pageNum)
            ->limit($pageSize)
            ->get();
//            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $shopCodes = $paginates->pluck('shopCode')->toArray();
        $shopInfos = collect(
            RmsShopRemote::getShopFieldsByCodes(
                $shopCodes,
                ['shopCode', 'name', 'formalUseAt']
            )['shopList'] ?? []
        )->keyBy('shopCode');

        $lists = $paginates->map(
            function ($item) use ($shopInfos) {

                // 开业时间，默认取rms，为0时，取预计开业时间
                $openTime = $shopInfos[$item->shopCode]['formalUseAt'] ?? 0;
                if (!$openTime) {
                    $openTime = (int)optional($item->shopLocationRel)->openTime;
                    $isOpen   = false;
                } else {
                    $isOpen = true;
                }

                $nowStepStatus = (int)$item->nowStepStatus;

                // tags
                // 是否 迁址
                $tagLocationStatus = false;
                if (!empty($item->mainProcessRel->childLocationOrder)) {
                    $tagLocationStatus = (bool)$item->mainProcessRel->childLocationOrder;
                }
                // 是否异常
                $exceptionMsg = optional($item->contractRel)->exceptionMsg;
                $isAbnormal   = !empty($exceptionMsg);
                // 合
                $isConfirm = $item->step < SignOrderEnum::STEP_2;
                // 多
                $shopCount = optional($item->contractRel)->shopCount ?? 1;
                $isDuoShop = $shopCount > 1;
                // 离
                $isQuit = false; // 未知
                //重
                $isKeyCity = $item->keyCity == '重点城市';

                $tags = OrderService::getOrderTags(
                    1,
                    $tagLocationStatus,
                    $item->contractStatus == OpenShopSignOrderModel::CONTRACT_STATUS_CHANGE,
                    $item->dissolveStatus > OpenShopSignOrderModel::DISSOLVE_STATUS_NORMAL && $item->status != SignOrderEnum::ORDER_STATUS_NO,
                    $isAbnormal,
                    $isConfirm,
                    $isDuoShop,
                    $isQuit,
                    false,
                    $isKeyCity
                );
                return [
                    'id'                => $item->id,
                    'orderNo'           => $item->orderNo,
                    'shopCode'          => 'KF' . $item->kfShopCode,
                    'userName'          => $userName = (string)$item->franchiseeRealName,
                    'shopName'          => $item->shopCode ? ($shopInfos[$item->shopCode]['name'] ?? '') : ($userName . '的店'),
                    'shopAddressPrefix' => $item->province . '-' . $item->city . '-' . $item->district,
                    'signTime'          => $item->signTime ? date('Y-m-d', $item->signTime) : '-',
                    'openTime'          => $openTime ? date('Y-m-d', $openTime) : '-',
                    'isOpen'            => $isOpen,
                    'statusText'        => MissionTemplateEnum::STEP_STATUS_TEXT[$nowStepStatus] ?? '-',
                    'tags'              => $tags,
                    'shopId'            => $item->shopId,
                ];
            }
        );

        return [
            'count'    => 0,
            'pageMax'  => 0,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
            'list'     => $lists,
        ];

    }


    /**
     * 分公司列表
     * @param $lng
     * @param $lat
     * @param int $rmsUserId
     * @param string $type
     * @return array
     * @throws ValidationException
     */
    public static function clueClassify($lng, $lat, int $rmsUserId, string $type = ''): array
    {
        $getUserRole = UserRoleService::getUserRole($rmsUserId);
        $role        = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;

        return Cache::remember(
            'kms:clueClassifyCache:' . md5(
                json_encode(
                    [
                        'rmsUserId'   => $rmsUserId,
                        'role'        => $role,
                        'getUserRole' => $getUserRole,
                        'type'        => $type,
                    ]
                )
            ), 20 * 60, function () use ($type, $role, $getUserRole) {

            if ($type == 'site') {// 选址tab-省市区
                $provinces = [];
                if (!$getUserRole['userResponsibleArea']['all'] && $getUserRole['homeBranchOffice']['branchOfficeProvince']) {
                    $provinces = $getUserRole['homeBranchOffice']['branchOfficeProvince'];
                }
                $aMapArea  = AmapAreaModel::query()->get();
                $selection = [];

                collect($aMapArea)
                    ->where('level', AmapAreaModel::LEVEL_PROVINCE)
                    ->map(
                        function ($province) use ($aMapArea, $provinces, &$selection) {
                            if (!$provinces || in_array($province['code'], $provinces)) {
                                array_push(
                                    $selection,
                                    [
                                        'label'    => $province['label'],
                                        'type'     => HomeService::REGION_SELECTION_TYPE_2,
                                        'value'    => $province['code'],
                                        'children' => $aMapArea
                                            ->where('pCode', $province['code'])
                                            ->map(
                                                function ($area) use ($aMapArea) {
                                                    return [
                                                        'label'    => $area['label'],
                                                        'value'    => $area['code'],
                                                        'type'     => HomeService::REGION_SELECTION_TYPE_3,
                                                        'children' => $aMapArea->where('pCode', $area['code'])
                                                            ->map(
                                                                function ($isDistrict) {
                                                                    return [
                                                                        'label' => $isDistrict['label'],
                                                                        'value' => $isDistrict['code'],
                                                                        'type'  => HomeService::REGION_SELECTION_TYPE_5,
                                                                    ];
                                                                }
                                                            )->values()->toArray()
                                                    ];
                                                }
                                            )->values()->toArray()
                                    ]
                                );
                            }
                        }
                    );

                if ($getUserRole['role'] == UserRoleService::ROLE_BASE_CITY_MANAGER || $getUserRole['role'] == UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER) {
                    if (!$getUserRole['userResponsibleArea']['all'] && $getUserRole['homeBranchOffice']['branchOfficeCity']) {
                        $selection = collect($selection[0]['children'] ?? [])
                            ->whereIn('value', $getUserRole['homeBranchOffice']['branchOfficeCity'])
                            ->values()
                            ->toArray();
                    }
                }
                return [
                    'list'    => $selection,
                    'chooses' => [],
                ];
            }

            if ($getUserRole['role'] == UserRoleService::ROLE_BASE_WAR_REGION ||
                $getUserRole['homeBranchOffice']['isHeadOfficeAttachUser']
            ) {
                $selection = HomeService::defaultWarRegionSelection(1);

                $warZones = collect($getUserRole['warZone'])->pluck('id')->toArray();
                if (!$getUserRole['homeBranchOffice']['isHeadOfficeAttachUser'] && $warZones) {
                    $selection = collect($selection)
                        ->whereIn('value', $warZones)
                        ->values()
                        ->toArray();
                }
            } else {
                $selection = HomeService::defaultProvinceRegionSelection(1);

                if (!$getUserRole['userResponsibleArea']['all'] && $getUserRole['homeBranchOffice']['branchOfficeProvince']) {
                    $selection = collect($selection)
                        ->whereIn(
                            'value',
                            $getUserRole['homeBranchOffice']['branchOfficeProvince']
                        )
                        ->values()
                        ->toArray();
                }
                if ($getUserRole['role'] == UserRoleService::ROLE_BASE_CITY_MANAGER || $getUserRole['role'] == UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER) {
                    if (!$getUserRole['userResponsibleArea']['all'] && $getUserRole['homeBranchOffice']['branchOfficeCity']) {
                        $selection = collect($selection[0]['children'] ?? [])
                            ->whereIn('value', $getUserRole['homeBranchOffice']['branchOfficeCity'])
                            ->values()
                            ->toArray();
                    }
                }
            }

            return [
                'list'    => $selection,
                'chooses' => [],
            ];
        }
        );
    }


    /**
     * 房源列表
     * @param int $rmsUserId
     * @param array $search
     * @return array
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function houseResourcesList(int $rmsUserId, array $search): array
    {
        $getUserRole = UserRoleService::getUserRole($rmsUserId);
        $role        = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        if (in_array(
            $role, [
                UserRoleService::ROLE_BASE_SUPERVISOR, UserRoleService::ROLE_BASE_PREPARE,
                UserRoleService::ROLE_SPECIAL_3, UserRoleService::ROLE_SPECIAL_4, UserRoleService::ROLE_SPECIAL_5
            ]
        )) {
            return [
                'list'     => [],
                'count'    => 0,
                'pageNum'  => $search['pageNum'],
                'pageSize' => $search['pageSize']
            ];// 暂无数据
        }
        $allArea      = $getUserRole['userResponsibleArea']['all'] ?? false;
        $branchOffice = $getUserRole['homeBranchOffice']['branchOffice'] ?? [];

        if (!$allArea && $branchOffice && !$search['branchId'] && !$search['provinceCode'] && !$search['cityCode'] && !$search['areaCode']) {//获取对应分公司id
            $branchIds     = array_column($branchOffice, 'id');
            $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo($branchIds);
            if ($getRegionInfo) {
                $search['provinceCode'] = array_column($getRegionInfo, 'provinceCode');
            }
        }
        if ($search['branchId'] && !$search['provinceCode'] && !$search['cityCode'] && !$search['areaCode']) {
            $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo([$search['branchId']]);
            if ($getRegionInfo) {
                $search['provinceCode'] = array_column($getRegionInfo, 'provinceCode');
            }
        }


        $userInfos = KmsUser::getUserInfo([], '选址开发中心');//大客户部用户信息

        $paginator = OpenShopSiteLocationModel::query()
            ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_HOUSING])
            ->when(
                $search['orderNo'], function ($query) use ($search) {
                $query->where('orderNo', $search['orderNo']);
            }
            )
            ->when(
                $search['name'], function ($query) use ($search) {
                //区分编号与地址搜索
                if (strpos($search['name'], 'fy') !== false ||
                    strpos($search['name'], 'FY') !== false ||
                    strpos($search['name'], 'Fy') !== false ||
                    strpos($search['name'], 'fY') !== false ||
                    is_numeric($search['name'])) {
                    $query->where('orderNo', $search['name']);
                } else {
                    $query->where(
                        function ($query) use ($search) {
                            $query->orWhere('address', 'like', "%{$search['name']}%")
                                ->orWhere('siteAddress', 'like', "%{$search['name']}%")
                                ->orWhere('cityArea', 'like', "%{$search['name']}%");
                        }
                    );
                }
            }
            )
            ->when(
                !in_array(
                    $role, [
                        UserRoleService::ROLE_BASE_KAM,
                    ]
                ), function ($query) use ($rmsUserId, $userInfos, $role, $search) {
                $query->when(
                    $search['provinceCode'] || $search['cityCode'] || $search['areaCode'], function ($query) use ($search) {
                    $query->where(
                        function ($query) use ($search) {
                            $query->when(
                                $search['provinceCode'], function ($query) use ($search) {
                                $query->whereIn("provinceCode", $search['provinceCode']);
                            }
                            )->when(
                                $search['cityCode'], function ($query) use ($search) {
                                $query->whereIn("cityCode", $search['cityCode']);
                            }
                            )->when(
                                $search['areaCode'], function ($query) use ($search) {
                                $query->whereIn("areaCode", $search['areaCode']);
                            }
                            );
                        }
                    );
                }
                )->when(
                    !in_array(
                        $role, [
                            UserRoleService::ROLE_SPECIAL_1,
                            UserRoleService::ROLE_SPECIAL_2,
                        ]
                    ) && $userInfos, function ($query) use ($rmsUserId, $search, $userInfos) {
                    $query->where(
                        function ($query) use ($rmsUserId, $userInfos, $search) {
                            $query->whereNotIn('createdByUid', array_keys($userInfos));//查询非大客户房源
                        }
                    );
                }
                )->when(
                    $search['isOwn'], function ($query) use ($rmsUserId) {
                    $query->where('createdByUid', $rmsUserId);
                }
                );
            }
            )
            ->when(
                in_array(
                    $role, [
                        UserRoleService::ROLE_BASE_KAM,
                    ]
                ), function ($query) use ($rmsUserId) {
                $query->where('createdByUid', $rmsUserId);
            }
            )
            ->when(
                $search['clueStatus'], function ($query) use ($search) {
                $query->whereIn('clueStatus', $search['clueStatus']);
            }
            )
            ->when(
                $search['shopModelType'], function ($query) use ($search) {
                $query->whereIn('shopModelType', $search['shopModelType']);//门店模型类型
            }
            )
            ->when(
                $search['area'], function ($query) use ($search) {
                $query->where(
                    function ($query) use ($search) {
                        foreach ($search['area'] as $value) {
                            if (is_array(OpenShopSiteLocationModel::HOUSE_SEARCH_AREA_ORM_MAPPING[$value])) {
                                $query->orWhereBetween(
                                    'area',
                                    OpenShopSiteLocationModel::HOUSE_SEARCH_AREA_ORM_MAPPING[$value]
                                );
                            } else {
                                $query->orWhere(
                                    'area', '>',
                                    OpenShopSiteLocationModel::HOUSE_SEARCH_AREA_ORM_MAPPING[$value]
                                );
                            }

                        }
                    }
                );
            }
            )
            ->when(
                $search['grade'], function ($query) use ($search) {
                $query->whereIn('shopGrade', $search['grade']);
            }
            )
            ->when(
                $search['rent'], function ($query) use ($search) {
                $query->where(
                    function ($query) use ($search) {
                        foreach ($search['rent'] as $value) {
                            if (is_array(OpenShopSiteLocationModel::HOUSE_SEARCH_RENT_ORM_MAPPING[$value])) {
                                $query->orWhereBetween(
                                    'clueRent',
                                    OpenShopSiteLocationModel::HOUSE_SEARCH_RENT_ORM_MAPPING[$value]
                                );
                            } else {
                                $query->orWhere(
                                    'clueRent', '>',
                                    OpenShopSiteLocationModel::HOUSE_SEARCH_RENT_ORM_MAPPING[$value]
                                );
                            }

                        }
                    }
                );
            }
            )
            ->when(
                true, function ($query) use ($search) {
                switch ($search['groupBy']) {
                    case OpenShopSiteLocationModel::HOUSE_GROUP_BY_RENT_ASC:
                        $query->orderBy('clueRent');
                        break;
                    case OpenShopSiteLocationModel::HOUSE_GROUP_BY_RENT_DESC:
                        $query->orderByDesc('clueRent');
                        break;
                    case OpenShopSiteLocationModel::HOUSE_GROUP_BY_AREA_ASC:
                        $query->orderBy('area');
                        break;
                    case OpenShopSiteLocationModel::HOUSE_GROUP_BY_AREA_DESC:
                        $query->orderByDesc('area');
                        break;
                    default:
                        $query->orderByDesc('updatedAt');
                }
            }
            )
            ->with(['uploadFileResourceRel'])
            ->select(['*'])
            ->offset($search['pageNum'])
            ->limit($search['pageSize'])
            ->get();
//            ->paginate($search['pageSize'], ['*'], 'pageNum', $search['pageNum']);

        $body = RmsUserService::getRmsUserInfoByUserIds($paginator->pluck('createdByUid')->toArray());
        $list = $paginator->map(
            function ($item) use (&$clueCount, &$putCount, &$successCount, $body) {
                if ($item->uploadFileResourceRel->toArray()) {
                    $image = $item->uploadFileResourceRel[0]->formatUrl ?? '';
                    foreach ($item->uploadFileResourceRel as $value) {
                        if ($value->position == UploadFileResourceEnum::SHOP_ADDRESS_FRONT_PHOTO) {
                            $image = $value->formatUrl;
                        }
                    }
                } else {
                    $image = 'https://file.51kuafu.com/52/42/6f191617b85d80427702dcf6e938872fa6bbb4552898631ca5a13787bdab.png'; //添加默认图片
                }
                $cityAreaArr = explode('-', $item->cityArea);
                if (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1]) && isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2])) {
                    $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1] . '-' . $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2];
                } elseif (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1])) {
                    $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_1];
                } elseif (isset($cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2])) {
                    $cityArea = $cityAreaArr[OpenShopSiteLocationModel::CITY_AREA_ARRAY_INDEX_2];
                } else {
                    $cityArea = '';
                }
                $owner = '-';
                foreach (($body['data'] ?? []) as $user) {
                    if ($user['id'] == $item->createdByUid) {
                        $owner = $user['username'];
                    }
                }
                return [
                    'id'            => $item->id,
                    'orderNo'       => $item->clueStatus == OpenShopSiteLocationModel::CLUE_STATUS_6 ? 'FY' . $item->id : $item->orderNo,
                    'image'         => $image,
                    'address'       => $item->address,
                    'cityArea'      => $cityArea,
                    'statusText'    => OpenShopSiteLocationModel::CLUE_STATUS_MAP[$item->clueStatus],
                    'clueStatus'    => $item->clueStatus,
                    'recommender'   => $owner,
                    'shopGrade'     => OpenShopSiteLocationModel::HOUSE_SHOP_GRADE_SIFT_MAPPING[$item->shopGrade] ?? '',
                    'putTime'       => $item->putAt ? date('Y-m-d H:i:s', $item->putAt) : '-',
                    'area'          => $item->area ? $item->area . '㎡' : '-',
                    'clueRentMonth' => ceil($item->fixedRent / 12),
                    'clueRentDay'   => ceil($item->fixedRent / 365),
                    'number'        => $item->orderNo,
                ];
            }
        );
        return [
            'list'     => $list,
            'count'    => 0,
            'pageNum'  => $search['pageNum'],
            'pageSize' => $search['pageSize'],
        ];
    }

    /**
     * 落址
     * @param int $rmsUserId
     * @param array $userIds
     * @param array $search
     * @return array
     * @throws ValidationException
     */
    public static function siteLocationsTotal(int $rmsUserId, array $userIds, array $search): array
    {
        $getUserRole = UserRoleService::getUserRole($rmsUserId);
        $role        = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        $allArea     = $getUserRole['userResponsibleArea']['all'] ?? false;
        if ((!$allArea && in_array($role, [UserRoleService::ROLE_BASE_SUPERVISOR, UserRoleService::ROLE_BASE_PREPARE])) || in_array($role, [UserRoleService::ROLE_SPECIAL_4])) {
            return ['data' => [], 'tagData' => []];// 暂无数据
        }
        $branchOffice = $getUserRole['homeBranchOffice']['branchOffice'] ?? [];

        if (!$allArea && $branchOffice && !$search['branchId'] && !$search['provinceCodes'] && !$search['cityCodes'] && !$search['areaCodes']) {//获取对应分公司id
            $branchIds     = array_column($branchOffice, 'id');
            $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo($branchIds);
            if ($getRegionInfo) {
                $search['provinceCodes'] = array_column($getRegionInfo, 'provinceCode');
            }
        }
        if ($search['branchId'] && !$search['provinceCodes'] && !$search['cityCodes'] && !$search['areaCodes']) {
            $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo([$search['branchId']]);
            if ($getRegionInfo) {
                $search['provinceCodes'] = array_column($getRegionInfo, 'provinceCode');
            }
        }

        $orderNos = $rmsUserIds = [];
        if ($search['name']) {
            // 加盟商姓名
            OpenShopUserIdentityCardModel::query()
                ->with(['mainProcessRel'])
                ->where('name', 'like', "%{$search['name']}%")
                ->get()
                ->each(
                    function ($item) use (&$orderNos) {
                        if ($item->mainProcessRel != null) {
                            foreach ($item->mainProcessRel as $value) {
                                $orderNos[] = $value->orderNo;
                            }
                        }
                    }
                );
            if (!$orderNos) {
                $orderNos = ['0'];
            }
        }
        if ($search['dealName']) {
            // 处理人
            $rmsUserIds = self::getRmsUserIdByUserName($search['dealName']);
        }

        $data = [
            'role'          => $role,
            'provinceCodes' => $search['provinceCodes'],
            'cityCodes'     => $search['cityCodes'],
            'areaCodes'     => $search['areaCodes'],
            'userIds'       => array_unique(array_merge($userIds, $rmsUserIds)),
            'allArea'       => $allArea,
            'rmsUserId'     => $rmsUserId,
            'search'        => $search,
            'orderNos'      => $orderNos,
        ];

        $isRel = 0;
        if (in_array($role, [UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT, UserRoleService::ROLE_BASE_KAM])) {
            $isRel = 1;//选址开发&大客户经理 查询关联自己的数据
        }
        // 选址

        return self::countSiteLocation($data, $search['isOperate'], $isRel, 1);
    }

    /**
     * 落址列表
     * @param int $rmsUserId
     * @param array $userIds
     * @param int $isOperate
     * @param int $pageNum
     * @param int $pageSize
     * @param array $search
     * @return array
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function siteLocationsList(int $rmsUserId, array $userIds, int $isOperate, int $pageNum, int $pageSize, array $search): array
    {
        $getUserRole = UserRoleService::getUserRole($rmsUserId);
        $role        = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        $allArea     = $getUserRole['userResponsibleArea']['all'] ?? false;
        if ((!$allArea && in_array($role, [UserRoleService::ROLE_BASE_SUPERVISOR, UserRoleService::ROLE_BASE_PREPARE])) || in_array($role, [UserRoleService::ROLE_SPECIAL_4])) {
            return [
                'list'     => [],
                'count'    => 0,
                'pageNum'  => $pageNum,
                'pageSize' => $pageSize,
            ];// 暂无数据
        }
        $branchOffice = $getUserRole['homeBranchOffice']['branchOffice'] ?? [];

        if (!$allArea && $branchOffice && !$search['branchId'] && !$search['provinceCodes'] && !$search['cityCodes'] && !$search['areaCodes']) {//获取对应分公司id
            $branchIds     = array_column($branchOffice, 'id');
            $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo($branchIds);
            if ($getRegionInfo) {
                $search['provinceCodes'] = array_column($getRegionInfo, 'provinceCode');
            }
        }

        if ($search['branchId'] && !$search['provinceCodes'] && !$search['cityCodes'] && !$search['areaCodes']) {
            $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo([$search['branchId']]);
            if ($getRegionInfo) {
                $search['provinceCodes'] = array_column($getRegionInfo, 'provinceCode');
            }
        }

        if ($isOperate) {// 只看自己处理的类型
            $search['types'] = array_unique(array_merge($search['types'], [self::TYPE_1, self::TYPE_2, self::TYPE_4, self::TYPE_5, self::TYPE_6]));
        }
        $siteLocationWhere = $siteMissWhere = [];
        if ($search['types']) {
            foreach ($search['types'] as $type) {
                switch ($type) {
                    case self::TYPE_1:
                        if (!$isOperate || ($isOperate && in_array($role, [UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT, UserRoleService::ROLE_BASE_KAM]))) {
                            $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_0, OpenShopSiteLocationModel::SITE_STATUS_1]);//提交选址
                        }
                        break;
                    case self::TYPE_2:
                        if (!$isOperate || ($isOperate && in_array($role, [UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT, UserRoleService::ROLE_BASE_KAM]))) {
                            $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_3]);//选址修改
                        }
                        break;
                    case self::TYPE_3:
                        if (!$isOperate) {
                            $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_4]);//完成落址
                        }
                        break;
                    case self::TYPE_4:
                        if (!$isOperate || ($isOperate && in_array($role, [UserRoleService::ROLE_BASE_PROVINCE, UserRoleService::ROLE_SPECIAL_1, UserRoleService::ROLE_SPECIAL_2, UserRoleService::ROLE_SPECIAL_3]))) {
                            $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_2, OpenShopSiteLocationModel::SITE_STATUS_10, OpenShopSiteLocationModel::SITE_STATUS_11]);//选址审批
                        }
                        break;
                    case self::TYPE_5:
                        if (!$isOperate || ($isOperate && in_array($role, [UserRoleService::ROLE_BASE_SITE_SELECTION_DEVELOPMENT, UserRoleService::ROLE_BASE_KAM]))) {
                            $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_21]);//合同上传
                        }
                        break;
                    case self::TYPE_6:
                        if (!$isOperate || ($isOperate && in_array($role, [UserRoleService::ROLE_SPECIAL_2, UserRoleService::ROLE_SPECIAL_5]))) {
                            $siteMissWhere = array_merge($siteMissWhere, [MissionTemplateEnum::STEP_STATUS_3]);          //开发待指派
                        }
                        break;
                    case self::TYPE_7:
                        if (!$isOperate) {
                            $siteLocationWhere = array_merge($siteLocationWhere, [OpenShopSiteLocationModel::SITE_STATUS_20]);//商家待确认
                        }
                        break;
                }
            }
        }
        $orderNos = $rmsUserIds = [];
        if ($search['name']) {
            // 加盟商姓名
            OpenShopUserIdentityCardModel::query()
                ->with(['mainProcessRel'])
                ->where('name', 'like', "%{$search['name']}%")
                ->get()
                ->each(
                    function ($item) use (&$orderNos) {
                        if ($item->mainProcessRel != null) {
                            foreach ($item->mainProcessRel as $value) {
                                $orderNos[] = $value->orderNo;
                            }
                        }
                    }
                );
            if (!$orderNos) {
                $orderNos = ['0'];
            }
        }

        if ($search['orderNo']) {
            $orderNos = [$search['orderNo']];// 搜索单号
        }

        if ($search['dealName']) {

            // 处理人
            $rmsUserIds = self::getRmsUserIdByUserName($search['dealName']);
        }
        $siteMissFinish = 0;

        $data = [
            'role'              => $role,
            'siteLocationWhere' => $siteLocationWhere,
            'siteMissWhere'     => $siteMissWhere,
            'siteMissFinish'    => $siteMissFinish,
            'userIds'           => array_unique(array_merge($userIds, $rmsUserIds)),
            'provinceCodes'     => $search['provinceCodes'],
            'cityCodes'         => $search['cityCodes'],
            'areaCodes'         => $search['areaCodes'],
            'allArea'           => $allArea,
            'rmsUserId'         => $rmsUserId,
            'search'            => $search,
            'orderNos'          => $orderNos,
            'isOperate'         => $isOperate,
            'pageSize'          => $pageSize,
            'pageNum'           => $pageNum,
        ];

        // 选址
        return self::getSiteLocationList($data, 1);
    }

    /**
     * 任务记录
     * @param string $orderNo
     * @return array
     */
    public static function processList(string $orderNo): array
    {
        return OpenShopSiteMissionModel::query()
            ->with(['fsUserRel'])
            ->where('orderNo', $orderNo)
            ->orderByDesc('createdAt')
            ->get()
            ->map(
                function ($item) {
                    return [
                        "id"              => $item->id,
                        "stepStatus"      => $item->stepStatus,
                        "missionName"     => $item->missionName,
                        "status"          => $item->status,
                        "statusText"      => SiteMissionEnum::STATUS_TEXT[$item->status] ?? "",
                        "createdAt"       => $item->createdAt->toDateTimeString(),
                        "dealUid"         => $item->dealUid,
                        "createdUserName" => ($item->fsUserRel->nickname ?? '') . '(' . ($item->fsUserRel->name ?? '') . ')',
                    ];
                }
            )
            ->toArray();
    }

    /**
     * 照片素材
     * @param string $orderNo
     * @param int $pageNum
     * @param int $pageSize
     * @return array
     */
    public static function photoList(string $orderNo, int $pageNum, int $pageSize): array
    {
        $orderDetail = OpenShopSignOrderModel::orderDetail($orderNo);
        $shopCode    = $orderDetail->getIterator()->current()->shopCode;
        $paginator   = AlbumResourceModel::query()
            ->where("poiName", "like", "%{$shopCode}%")
            ->where("poiType", AlbumResourceModel::POI_TYPE_WG_KF_SHOP)
            ->where("isInRecycleBin", 0)
            ->where("isDeleted", 0)
            ->orderByDesc('createdAt')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $list = $paginator->map(
            function ($item) {
                return [
                    'id'              => $item->id,
                    'poiNo'           => $item->poiNo,
                    'poiType'         => $item->poiType,
                    'poiName'         => $item->poiName,
                    'date'            => $item->date,
                    'weekDay'         => $item->weekDay,
                    'creatorUsername' => $item->creatorUsername,
                    'type'            => $item->type,
                    'originalUrl'     => $item->originalUrl,
                    'previewUrl'      => $item->previewUrl,
                ];
            }
        );

        /*$data = [];
        if ($list) {
            foreach ($list as $v) {
                $data[$v['date']][$v['creatorUsername']][] = $v;
            }
        }*/
        return [
            'list'     => $list,
            'count'    => $paginator->total(),
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }

    /**
     * 年费订单+续签订单列表
     * @param string $orderNo
     * @return array
     * @throws ValidationException
     */
    public static function shopOrderList(string $orderNo): array
    {
        $data        = [];
        $orderDetail = OpenShopSignOrderModel::orderDetail($orderNo);
        // 年费订单
        $feeAnnualOrderList = FeeAnnualOrderService::getList(
            [], PermissionService::PERMISSION_ALL, -1, '',
            (int)$orderDetail->getIterator()->current()->shopCode, 10, 1
        );
        if ($feeAnnualOrderList && $feeAnnualOrderList['count']) {
            $feeAnnualOrderData = json_decode($feeAnnualOrderList['list'], true) ?? [];
            if ($feeAnnualOrderData) {
                foreach ($feeAnnualOrderData as &$v) {
                    $v['source']     = 1;
                    $v['sourceText'] = '年费订单';
                }
                $data = $feeAnnualOrderData;
            }
        }
        // 续签订单
        $renewOrderList = RenewOrderService::renewWorkOrderGroupList(
            (object)[
                "pageSize" => "10",
                "pageNum"  => "1",
                "param"    => '',
                "search"   => (int)$orderDetail->getIterator()->current()->shopCode,
                "type"     => "0"
            ]
        );
        if ($renewOrderList && $renewOrderList['total']) {
            collect($renewOrderList['list'])
                ->map(
                    function ($item) use (&$data) {
                        $item['source']     = 2;
                        $item['sourceText'] = '续签订单';
                        $data[]             = $item;
                    }
                );
        }
        return $data;
    }

    /**
     * 门店风云榜
     * @param array $searchData
     * @param int $rmsUserId
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function getWindCloudRank(array $searchData, int $rmsUserId)
    {
        $getUserRole   = UserRoleService::getUserRole($rmsUserId);
        $role          = $getUserRole['role'] ?? UserRoleService::ROLE_SPECIAL_NO_ACCESS;
        $provinceCodes = $getUserRole['userResponsibleArea']['area']['province'] ?? [];
        $cityCodes     = $getUserRole['userResponsibleArea']['area']['city'] ?? [];
        $areaCodes     = $getUserRole['userResponsibleArea']['area']['district'] ?? [];
        $allArea       = $getUserRole['userResponsibleArea']['all'] ?? false;

        $shopIds = [];
        if ($allArea) {
            $provinceCodes = $cityCodes = $areaCodes = [];
        }
        if (!$allArea && $role == UserRoleService::ROLE_BASE_SUPERVISOR) {// 督导
            $shopIds = OpenShopOrderManagerModel::getShopIdByUid([$rmsUserId])[$rmsUserId] ?? [];
        }

        // 页面搜索
        $city      = (string)($searchData['city'] ?? '');
        $province  = (string)($searchData['province'] ?? '');
        $district  = (string)($searchData['district'] ?? '');
        $branch    = (string)($searchData['branch'] ?? '');
        $warZoneId = (int)($searchData['warZoneId'] ?? 0);  //战区Id

        if ($branch || $city || $province || $district || $warZoneId) {
            $provinceCodes = $cityCodes = $areaCodes = $shopIds = [];

            if ($warZoneId) {// 搜索战区id
                $branchOffice  = self::getBranchByWarZoneIds([], $warZoneId);
                $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo(array_column($branchOffice, 'id'));
                if ($getRegionInfo) {
                    $provinceCodes = array_column($getRegionInfo, 'provinceCode');
                }
            }
        }

        $data = array_merge(
            $searchData, [
                'kmsUserId'     => $rmsUserId,
                'provinceCodes' => $provinceCodes ? implode(',', $provinceCodes) : '',
                'cityCodes'     => $cityCodes ? implode(',', $cityCodes) : '',
                'areaCodes'     => $areaCodes ? implode(',', $areaCodes) : '',
                'shopIds'       => $shopIds ? implode(',', $shopIds) : '',
            ]
        );
        return RmsShopRemote::getWindCloudRank($data);
    }

    /**
     * 省市区code转中文查询
     * @param $allArea
     * @param $branchOffice
     * @param $search
     * @return array
     */
    public static function getCodeConversion($allArea, $branchOffice, $search): array
    {
        $branch = $province = $city = $district = [];
        if (!$allArea && $branchOffice && !$search['warZoneId'] && !$search['branchId'] && !$search['province'] && !$search['city'] && !$search['district']) {
            $branchIds     = array_column($branchOffice, 'id');//获取对应分公司id
            $getRegionInfo = OpenShopOrganizationRegionMappingModel::getRegionInfo($branchIds);
            if ($getRegionInfo) {
                $province = array_column($getRegionInfo, 'provinceName');
            }
        }
        if ($search['warZoneId'] && !$search['branchId'] && !$search['province'] && !$search['city'] && !$search['district']) {
            $branchOffice = self::getBranchByWarZoneIds([], (int)$search['warZoneId']);// 搜索战区id
            if ($branchOffice) {
                $province = OpenShopOrganizationRegionMappingModel::query()
                    ->whereIn('manageId', array_column($branchOffice, 'id'))
                    ->pluck('provinceName')->toArray();
            }
        }
        if ($search['branchId'] && !$search['province'] && !$search['city'] && !$search['district']) {
            $province = OpenShopOrganizationRegionMappingModel::query()
                ->where('manageId', $search['branchId'])
                ->pluck('provinceName')->toArray();
        }
        if ($search['province']) {
            $province = [$search['province']];
        }
        if ($search['city']) {
            $city = [$search['city']];
        }
        if ($search['district']) {
            $district = [$search['district']];
        }
        return [
            'branch'   => $branch,
            'province' => $province,
            'city'     => $city,
            'district' => $district,
        ];
    }

    /**
     * 查询ck数据库中门店数据
     * @param $allArea
     * @param $branchOffice
     * @param $search
     * @param array $status
     * @param array $businessShopCodes
     * @return array
     */
    public static function getShopCodesByCkDb($allArea, $branchOffice, $search, array $status = [], array $businessShopCodes = []): array
    {
        $shopIds = $shopCodesByCK = $signShopCodes = [];
        // 签约时间取 回款时间
        if ($search['contractStartTime'] && $search['contractEndTime']) {
            $signShopCodes = GyShopSignCHModel::buildHomeSearchQuery(HomeService::REGION_SELECTION_TYPE_0, '')
                ->when(
                    $search['contractStartTime'] && $search['contractEndTime'],
                    function ($query) use ($search) {
                        $query->whereBetween('paybackTime', [$search['contractStartTime'], $search['contractEndTime']]);
                    }
                )
                ->get()
                ->pluck("contractNumber")->map(
                    function ($shopCode) {
                        $shopCode = str_replace('KF', '', $shopCode);
                        return ltrim($shopCode, "0");
                    }
                )->values()->toArray();
            if (!$signShopCodes) {
                $signShopCodes = ['-1'];
            }
        }

        if ($businessShopCodes) {// 存在活跃数据时 正常营业门店=正常营业状态+昨日活跃门店
            $shopCodes     = GyCloseShopCHModel::buildHomeSearchQuery(HomeService::REGION_SELECTION_TYPE_0, '')
                ->when(
                    $status, function ($query) use ($status) {
                    $query->whereIn('status', $status);
                }
                )
                ->get()
                ->pluck('berthNumber')->map(
                    function ($shopCode) {
                        return ltrim($shopCode, '0');
                    }
                )->values()->toArray();
            if ($signShopCodes && $signShopCodes != ['-1']) {
                $signShopCodes = array_unique(array_merge($signShopCodes, $shopCodes, $businessShopCodes));
            } else {
                $signShopCodes = array_unique(array_merge($shopCodes, $businessShopCodes));
            }
        }

        if ($signShopCodes) {
            foreach ($signShopCodes as $k => $v) {
                if (strlen($v) < 4) {// 店铺号前面补0
                    $signShopCodes[$k] = str_pad($v, 4, '0', STR_PAD_LEFT);
                }
            }
        }

        // 省市区code转中文查询
        $getCodeConversion = self::getCodeConversion($allArea, $branchOffice, $search);
        $shopCodesByCK     = GyCloseShopCHModel::buildHomeSearchQuery(HomeService::REGION_SELECTION_TYPE_0, '')
            ->when(
                $status && !$businessShopCodes, function ($query) use ($status) {
                $query->whereIn('status', $status);
            }
            )
            ->when(
                $signShopCodes, function ($query) use ($signShopCodes) {
                $query->whereIn('berthNumber', $signShopCodes);
            }
            )
            ->when(
                $getCodeConversion['province'], function ($query) use ($getCodeConversion) {
                $query->whereIn('storeProvince', $getCodeConversion['province']);
            }
            )
            ->when(
                $getCodeConversion['city'], function ($query) use ($getCodeConversion) {
                $query->whereIn('storeLocation', $getCodeConversion['city']);
            }
            )
            ->when(
                $getCodeConversion['district'], function ($query) use ($getCodeConversion) {
                $query->whereIn('districtOrCounty', $getCodeConversion['district']);
            }
            )
            ->when(
                $search['startBusinessStartTime'] && $search['startBusinessEndTime'],
                function ($query) use ($search) {
                    $query->whereBetween("openingDate", [$search['startBusinessStartTime'], $search['startBusinessEndTime']]);//开业日期
                }
            )
            ->when(
                $search['siteStartTime'] && $search['siteEndTime'],
                function ($query) use ($search) {
                    $query->whereBetween("confirmSiteLocationTime", [$search['siteStartTime'], $search['siteEndTime']]);//确址时间
                }
            )
            ->when(
                $search['tagIds'], function ($query) use ($search) {
                $query->whereIn("secondaryState", $search['tagIds']);//筹备标签Id搜索
            }
            )
            ->get()
            ->pluck("berthNumber")->map(
                function ($shopCode) {
                    return ltrim($shopCode, "0");
                }
            )->values()->toArray();
        if (!$shopCodesByCK) {
            $shopCodesByCK = ['-1'];
        }

        return ['shopIds' => $shopIds, 'shopCodes' => $shopCodesByCK];
    }

    /**
     * @param $username
     * @param $shopCodes
     * @param $search
     * @param $rmsUserId
     * @param $role
     * @param $businessStatus
     * @param $getShopCodesByCkDb
     */
    public static function baseQuery($username, $shopCodes, $search, $rmsUserId, $role, $businessStatus, $getShopCodesByCkDb)
    {
        $status = [SignOrderEnum::ORDER_STATUS_OK];
        if (in_array(MissionTemplateEnum::STEP_STATUS_999, $businessStatus)) {// 订单完成
            $status = [SignOrderEnum::ORDER_STATUS_OK, SignOrderEnum::ORDER_STATUS_COMPLETE];
        }
        return OpenShopSignOrderModel::query()
            ->leftJoin('open_shop_main_process', 'open_shop_main_process.id', '=', 'open_shop_sign_order.mainProcessId')
            ->leftJoin('guanyuan_sync_shop_list', 'guanyuan_sync_shop_list.code', '=', 'open_shop_sign_order.shopCode')
            ->whereIn('open_shop_sign_order.status', $status)
            ->when(
                in_array(MissionTemplateEnum::STEP_STATUS_999, $businessStatus), function ($query) {
                $query->whereRaw('open_shop_sign_order.id IN ( SELECT min( id ) FROM open_shop_sign_order where status in (1,2) GROUP BY shopCode ) ');
            }
            )
            ->when(
                $getShopCodesByCkDb, function ($query) use ($getShopCodesByCkDb) {
                $query->whereIn('open_shop_sign_order.shopCode', $getShopCodesByCkDb['shopCodes']);
            }
            )
            ->when(
                $businessStatus, function ($query) use ($businessStatus) {
                $query->whereIn('open_shop_main_process.nowStepStatus', $businessStatus);
            }
            )
            ->when(
                $role == UserRoleService::ROLE_BASE_PREPARE, function ($query) use ($rmsUserId) {//筹备
                $query->leftJoin('open_shop_site_mission', 'open_shop_site_mission.orderNo', '=', 'open_shop_sign_order.orderNo')
                    ->where('open_shop_site_mission.dealUid', $rmsUserId)
                    ->where('open_shop_site_mission.isShow', 1)
                    ->where('open_shop_site_mission.orderStatus', 1)
                    ->where('open_shop_site_mission.isDeleted', 0);
            }
            )
            ->when(
                $role == UserRoleService::ROLE_BASE_SUPERVISOR, function ($query) use ($rmsUserId) {//督导
                $query->leftJoin('open_shop_order_manager', 'open_shop_order_manager.mainProcessId', '=', 'open_shop_main_process.id')
                    ->where('open_shop_order_manager.isDeleted', 0)
                    ->where('open_shop_order_manager.managerUid', $rmsUserId)
                    ->where('open_shop_order_manager.type', OpenShopOrderManagerModel::MANAGER_TYPE_5);//督导
            }
            )
            ->when(
                $search['shopGrade'] || $search['shopType'],
                function ($query) use ($search) {
                    $query->when(
                        $search['shopGrade'],
                        function ($query) use ($search) {
                            $query->whereIn("guanyuan_sync_shop_list.shopGrade", $search['shopGrade']);//门店最近营业额评级搜索
                        }
                    )->when(
                        $search['shopType'],
                        function ($query) use ($search) {
                            $query->whereIn("guanyuan_sync_shop_list.storeType", $search['shopType']);//门店最近营业额评级搜索
                        }
                    );
                }
            )
            ->when(
                $shopCodes || $username, function ($query) use ($username, $shopCodes) {
                $query->where(
                    function ($query) use ($username, $shopCodes) {
                        $query->when(
                            $shopCodes, function ($query) use ($shopCodes) {
                            $query->whereIn('open_shop_sign_order.shopCode', $shopCodes);
                        }
                        )->when(
                            $username, function ($query) use ($username) {
                            $query->orWhere('guanyuan_sync_shop_list.franchiseeRealName', 'like', "%{$username}%");
                        }
                        );
                    }
                );
            }
            )
            ->when(
                $search['cruiseOrderStatus'],
                function ($query) use ($search) {
                    $query->leftJoin('cruise_order', 'cruise_order.orderNo', '=', 'open_shop_sign_order.orderNo')
                        ->where('cruise_order.type', CruiseOrderModel::TYPE_NEW_SHOP_HELP)
                        ->whereIn("cruise_order.status", $search['cruiseOrderStatus']);
                }
            );
    }


    /**
     * 查询近30天有营业数据的门店
     * @return array
     */
    public static function guanyuanSyncBusinessShopCodes(): array
    {
        $startDay = date('Y-m-d', strtotime('-30 day'));
        $endDay   = date('Y-m-d');
        return GuanyuanSyncShopBusinessModel::query()
            ->whereBetween('date', [$startDay, $endDay])
            ->groupBy('code')
            ->pluck('code')
            ->toArray();
    }

    /**
     * 模糊查询用户名称
     * @param $searchName
     * @return array
     * @throws GuzzleException
     */
    public static function getRmsUserIdByUserName($searchName): array
    {
        $rmsUserIds = [];
        try {
            $rmsUserIds = RmsUserRemote::getRmsUserIdByUserName($searchName);
            if (!$rmsUserIds) {
                $rmsUserIds = ['0'];
            } else {
                $rmsUserIds = array_column($rmsUserIds, 'id');
            }
        } catch (\Exception $e) {
            $rmsUserIds = ['0'];
        }
        return $rmsUserIds;
    }

    /**
     * 返回战区对应的分公司
     * @param array $warZoneIds
     * @param int $searchWarZoneId
     * @return array
     */
    public static function getBranchByWarZoneIds(array $warZoneIds, int $searchWarZoneId = 0): array
    {
        return WarZoneService::regionTree()
                ->map(
                    function (OpenShopRegionManageModel $regionManageModel) use ($warZoneIds, $searchWarZoneId) {
                        if ($searchWarZoneId) {
                            if ($regionManageModel->id != $searchWarZoneId) {
                                return [];
                            }
                        } elseif (!in_array($regionManageModel->id, $warZoneIds) && $warZoneIds) {
                            return [];
                        }
                        return $regionManageModel->regionMappingRel
                            ->map(
                                function (OpenShopRegionManageMappingModel $manageMappingModel) use ($warZoneIds) {
                                    return [
                                        'name' => $manageMappingModel->organizationManageRel->name ?? '',
                                        'id'   => $manageMappingModel->organizationManageRel->id ?? 0,
                                    ];
                                }
                            )->filter()->values()->toArray();
                    }
                )->filter()->values()->toArray()[0] ?? [];
    }
}
